1 33 package net.sf.jga.fn.algorithm; 34 35 import java.util.ArrayList ; 36 import java.util.Collection ; 37 import java.util.Collections ; 38 import net.sf.jga.fn.BinaryFunctor; 39 import net.sf.jga.fn.UnaryFunctor; 40 import net.sf.jga.fn.comparison.EqualTo; 41 import net.sf.jga.util.EmptyIterator; 42 import net.sf.jga.util.LookAheadIterator; 43 import java.util.Iterator ; 44 45 55 56 public class FindSequence<T> extends LookAheadFunctor<T> { 57 58 static final long serialVersionUID = 5277671793270812331L; 59 60 private Collection <? extends T> _pattern; 62 63 private BinaryFunctor<T,T,Boolean > _eq; 65 66 private int _length; 68 69 73 public FindSequence(Collection <? extends T> pattern) { 74 this(pattern, new EqualTo<T>()); 75 } 76 77 83 public FindSequence(Collection <? extends T> pattern, 84 BinaryFunctor<T,T,Boolean > eq ) 85 { 86 if (eq == null) 87 throw new IllegalArgumentException (); 88 89 _eq = eq; 90 _pattern = (pattern != null) ? pattern : new ArrayList <T>(); 91 92 _length = Math.max(pattern.size(), 1); 94 } 95 96 99 public Collection <? extends T> getPattern() { 100 return Collections.unmodifiableCollection(_pattern); 101 } 102 103 107 public BinaryFunctor<T,T,Boolean > getComparisonFn() { 108 return _eq; 109 } 110 111 113 120 public LookAheadIterator<T> fn(Iterator<? extends T> iterator) { 121 if (!iterator.hasNext() || _length == 0) { 123 return wrap(iterator, 1); 124 } 125 126 LookAheadIterator<T> lai = wrap(iterator, _length); 127 128 131 OUTER: 132 while (lai.hasNextPlus(_length)) { 133 int idx = 1; 134 135 for (T obj : _pattern) { 137 if (!_eq.fn(obj, lai.peek(idx))) { 143 lai.next(); 144 continue OUTER; 145 } 146 147 ++idx; 148 } 149 150 return lai; 153 } 154 155 return new LookAheadIterator<T>(new EmptyIterator<T>(), 1); 157 } 158 159 163 public void accept(net.sf.jga.fn.Visitor v) { 164 if (v instanceof FindSequence.Visitor) 165 ((FindSequence.Visitor)v).visit(this); 166 else 167 v.visit(this); 168 } 169 170 172 public String toString() { 173 return "FindSequence"; 174 } 175 176 178 182 public interface Visitor extends net.sf.jga.fn.Visitor { 183 public void visit(FindSequence host); 184 } 185 186 } 187 | Popular Tags |