1 33 package net.sf.jga.fn.algorithm; 34 35 import java.util.Iterator ; 36 import net.sf.jga.fn.UnaryFunctor; 37 import net.sf.jga.fn.UnaryFunctor; 38 import net.sf.jga.fn.comparison.EqualTo; 39 import net.sf.jga.fn.comparison.Equality; 40 import net.sf.jga.util.EmptyIterator; 41 import net.sf.jga.util.LookAheadIterator; 42 43 51 52 public class FindRepeated<T> extends LookAheadFunctor<T> { 53 54 static final long serialVersionUID = 2382887791885942503L; 55 56 private int _repeatCount; 58 59 private UnaryFunctor<T,Boolean > _eq; 61 62 66 public FindRepeated (int count, T value) { 67 this(count, new EqualTo<T>().bind2nd(value)); 68 } 69 70 74 public FindRepeated (int count, T value, Equality<T> eq) { 75 this(count, eq.bind2nd(value)); 76 } 77 78 83 public FindRepeated (int count, UnaryFunctor<T,Boolean > eq){ 84 if (count < 0) 85 throw new IllegalArgumentException ("count < 0"); 86 87 _repeatCount = count; 88 _eq = eq; 89 } 90 91 94 public int getRunLength() { 95 return _repeatCount; 96 } 97 98 102 public UnaryFunctor<T,Boolean > getComparisonFn() { 103 return _eq; 104 } 105 106 113 public LookAheadIterator<T> fn (Iterator <? extends T> iterator) { 114 if (!iterator.hasNext() || _repeatCount == 0) { 116 return new LookAheadIterator<T>(iterator, 1); 117 } 118 119 LookAheadIterator<T> lai = wrap(iterator, _repeatCount); 120 121 OUTER: 122 while (lai.hasNextPlus(_repeatCount)) { 123 124 for (int i = 1; i <= _repeatCount; ++i) { 126 T arg = lai.peek(i); 127 128 if ( ! _eq.fn(arg)) { 132 for (int j = i; j > 0; --j) { 133 lai.next(); 134 } 135 136 continue OUTER; 137 } 138 } 139 140 return lai; 143 } 144 145 return new LookAheadIterator<T>(new EmptyIterator<T>(), 1); 147 } 148 149 153 public void accept(net.sf.jga.fn.Visitor v) { 154 if (v instanceof FindRepeated.Visitor) 155 ((FindRepeated.Visitor)v).visit(this); 156 else 157 v.visit(this); 158 } 159 160 162 public String toString() { 163 return "FindRepeated["+_eq+"]"; 164 } 165 166 168 171 public interface Visitor extends net.sf.jga.fn.Visitor { 172 public void visit(FindRepeated host); 173 } 174 } 175 | Popular Tags |