Skip to content

Commit

Permalink
Optimization
Browse files Browse the repository at this point in the history
  • Loading branch information
deepeshpatel committed Jul 19, 2021
1 parent 20fc336 commit 5967a35
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* JNumberTools Library
* Copyright (c) 2021 Deepesh Patel (patel.deepesh@gmail.com)
*/
package io.github.deepeshpatel.jnumbertools.generator.permutation;


import io.github.deepeshpatel.jnumbertools.generator.AbstractGenerator;
import io.github.deepeshpatel.jnumbertools.generator.subset.SubsetGenerator;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class UniquePermutationInSizeRange<T> extends AbstractGenerator<T> {


private final int fromInclusive;
private final int toInclusive;

public UniquePermutationInSizeRange(Collection<T> seed, int fromInclusive, int toInclusive) {
super(seed);
this.fromInclusive = fromInclusive;
this.toInclusive = toInclusive;
}

@Override
public Iterator<List<T>> iterator() {
return new OnDemandIterator();
}

private class OnDemandIterator implements Iterator<List<T>> {

final Iterator<List<T>> subsetIterator;
Iterator<List<T>> currentIterator;
public OnDemandIterator() {
subsetIterator = new SubsetGenerator<>(seed, fromInclusive, toInclusive).iterator();
getNextIterator();
}

@Override
public boolean hasNext() {
if(currentIterator.hasNext()) {
return true;
}

if(!subsetIterator.hasNext()) {
return false;
}

return getNextIterator().hasNext();

}

private Iterator<List<T>> getNextIterator(){
currentIterator = new UniquePermutation<>(subsetIterator.next()).iterator();
return currentIterator;
}

@Override
public List<T> next() {
return currentIterator.next();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package io.github.deepeshpatel.jnumbertools.generator.permutation;

import io.github.deepeshpatel.jnumbertools.generator.JNumberTools;
import org.junit.Assert;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class UniquePermutationInSizeRangeTest {

@Test
public void shouldGenerateAllPermutationsInSizeRange2To3() {

int from = 0;
int to = 3;
List<Integer> input = IntStream.range(0,4).boxed().collect(Collectors.toList());

List<List<Integer>> outputViaKPermutation = new ArrayList<>();
for(int i=from; i<=to; i++) {
List<List<Integer>> collect = JNumberTools.permutationsOf(input)
.k(i)
.stream().collect(Collectors.toList());
outputViaKPermutation.addAll(collect);
}

List<List<Integer>> output = JNumberTools.permutationsOf(input)
.uniqueInSizeRange(from, to)
.stream().collect(Collectors.toList());

Assert.assertEquals(outputViaKPermutation.toString(), output.toString());

}
}

0 comments on commit 5967a35

Please sign in to comment.