-
Notifications
You must be signed in to change notification settings - Fork 0
/
DecimalFractionPeriodCollector.java
65 lines (55 loc) · 1.87 KB
/
DecimalFractionPeriodCollector.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
public class DecimalFractionPeriodCollector<T extends Integer> implements Collector<T, List<T>, StringBuilder> {
@Override
public Supplier<List<T>> supplier() {
return LinkedList::new;
}
@Override
public BiConsumer<List<T>,T> accumulator() {
return List::add;
}
@Override
public BinaryOperator<List<T>> combiner() {
return (x,y)->{ x.addAll(y); return x;};
}
@Override
public Set<Collector.Characteristics> characteristics() {
return Collections.emptySet();
}
@Override
public Function<List<T>,StringBuilder> finisher() {
return (source)->{
if(source.size()<2) throw new RuntimeException("at least two numbers should be provided to compute decimal fraction period");
List<T> digits=new LinkedList<T>();
List<T> remainders=new ArrayList<T>(50);
int dividend=source.get(0).intValue();
int divisor=source.get(1).intValue();
if(dividend>divisor) {
dividend=dividend%divisor;
}
int remainder;
do {
digits.add((T)Integer.valueOf(Integer.divideUnsigned(dividend, divisor)));
remainder=Integer.remainderUnsigned(dividend,divisor);
if(remainders.contains(remainder)) break;//stop if same remainder already has occurred
remainders.add((T)Integer.valueOf(remainder));
dividend=remainder*10;
}while(dividend>0);
int startIndex=remainders.indexOf(remainder);
StringBuilder fraction=new StringBuilder();
if(dividend>0 && startIndex>=0) {
fraction.append(digits.subList(startIndex+1, digits.size()));
}
return fraction;
};
}
}