view src/alice/test/codesegment/local/wordcount/WordCount.java @ 243:c70cd1b2caca

remove word_count bug
author sugi
date Wed, 08 May 2013 15:43:49 +0900
parents 3bcaf12cf877
children a560b92bfd72
line wrap: on
line source

package alice.test.codesegment.local.wordcount;

import java.nio.MappedByteBuffer;

import alice.codesegment.CodeSegment;
import alice.datasegment.CommandType;
import alice.datasegment.Receiver;

public class WordCount extends CodeSegment{
	
	private Receiver info1 = ids.create(CommandType.PEEK);
	private Receiver info2 = ids.create(CommandType.TAKE); 
	
	public WordCount(){
		info1.setKey("array");
		info2.setKey("range");
	}

	@Override
	public void run() {
		MappedByteBuffer buf = info1.asClass(MappedByteBuffer.class);
		Range r = info2.asClass(Range.class);
		int word_flag = 0;
	    int word_num = 0;
	    int line_num = 0;
	    
		for (int i = r.start; i < r.end; i++) {
			if ((char)buf.get(i) == 0x20) { // 空白                                                                                                                                
				word_flag = 1;
			} else if ((char)buf.get(i) == 0x0A) { // 改行
				line_num += 1;
				word_flag = 1;
			} else {
				word_num += word_flag;
				word_flag = 0;
			}
		}
		word_num += word_flag;
		if (!r.flag){
			if (((char)buf.get(r.end-1) == 0x0A||(char)buf.get(r.end-1) == 0x20) &&
					((char)buf.get(r.end) == 0x0A||(char)buf.get(r.end) == 0x20)){
				word_num--;
			}
		}
		
		Result result = new Result(line_num,word_num);
		ods.put("result", result);
	}

}