자바 오류코드
글쓴이: udanax / 작성시간: 일, 2007/04/15 - 8:10오후
테스트 코드는 아래와 같습니다.
라인단위에 text에 index를 주어 바이너리 서치하는건데,
가끔 존재하지만 안나오는게 있는것 같네요.
도대체 어디가 잘못된걸까요? ㅡㅡ?
package org.udanax.maplib.io; import java.io.*; import java.util.*; /** * Memory based IndexSearcher * @author udanax * @date 2007. 04. 13 */ public class IndexSearcher { private static long [] index; private static class temp_data { public final String text; public final long starts_at; public temp_data(String t, long l) { text = t; starts_at = l; } } private static class temp_cmp implements Comparator { public int compare(Object o1,Object o2) { return ((temp_data)o1).text.compareTo( ((temp_data)o2).text); } } /** * creats index table. You should do it once, * and rather store index table in file then. * This method has high peak memory usage but it is easy to optimize it. */ private static void buildIndex(RandomAccessFile file)throws Exception { List temp = new LinkedList(); String st; long p = file.getFilePointer(); while((st = file.readLine())!=null) { temp.add( new temp_data(st,p) ); p = file.getFilePointer(); } Collections.sort(temp,new temp_cmp()); index = new long[temp.size()]; int i=0; for(Iterator I=temp.iterator();I.hasNext();i++) { temp_data tt = ((temp_data)I.next()); //System.out.println("indexing :"+tt.text+" ["+tt.starts_at+"]"); index[i]=tt.starts_at; } } /** * returns position at which text starts or -1 if not found */ public static int binSearch(String text,RandomAccessFile file)throws Exception { int low = 0; int mid = index.length/2; int high = index.length-1; int filePos = 0; while (low <= high) { mid = (low + high) >> 1; filePos = index.length-mid; if(filePos >= index.length) { return -(low + 1); } else{ file.seek(index[filePos]); String tt = file.readLine(); int cmp = text.compareTo(tt); System.out.println("tt : "+ tt +" cmp : " + cmp); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return filePos; } } return -(low + 1); } public static void main(String args [] )throws Exception { RandomAccessFile f = new RandomAccessFile(args[0],"r"); buildIndex(f); System.out.print(binSearch("udanax",f)); System.out.println(); f.close(); } }
Forums:
댓글 달기