Find minimum number of packs that make a given value - java

I am trying to solve similar to this problem but with some modifications:
"Given a value V, if we want to make a change for V cents, and we have an infinite supply of each of C = { C1, C2, .. , Cm} valued coins, what is the minimum number of coins to make the change?"
Input: coins[] = {25, 10, 5}, V = 30
Output: Minimum 2 coins required
We can use one coin of 25 cents and one of 5 cents
In my case instead of just an array of numbers I have an array of objects. That in each object I have a qty and price.
I want to print the minimum number of objects that form the given qty, and after that print the price, something like:
2 x 5 9.95
1 x 3 5.95
I came to this code but I cannot find how to complete the task:
public static void main(String[] args) {
Product croissant = new Product("Croissant", "CF", null);
Pack CF_1 = new Pack(3, 5.95);
Pack CF_2 = new Pack(5, 9.95);
Pack CF_3 = new Pack(9, 16.99);
croissant.addPack(CF_1);
croissant.addPack(CF_2);
croissant.addPack(CF_3);
System.out.println(minCoins(croissant, 13));
}
static int minCoins(Product product, int V) {
// table[i] will be storing
// the minimum number of coins
// required for i value. So
// table[V] will have result
int table[] = new int[V + 1];
// Base case (If given value V is 0)
table[0] = 0;
// Initialize all table values as Infinite
for (int i = 1; i <= V; i++)
table[i] = Integer.MAX_VALUE;
// Compute minimum coins required for all
// values from 1 to V
for (int i = 1; i <= V; i++) {
// Go through all coins smaller than i
for (Pack pack : product.packList) {
if (pack.qty <= i) {
int sub_res = table[i - pack.qty];
if (sub_res != Integer.MAX_VALUE
&& sub_res + 1 < table[i])
table[i] = sub_res + 1;
}
}
}
return table[V];
}

You could get the list of packs that contribute to the minimum coins like below:
You start with given V then you look for the pack at which the table has value that is lesser by 1, because to reach V you must have had a value somewhere that is 1 lesser. If you found one, add it to the list, and reduce the next V by the quantity of the pack you found and continue.
Code is :
void printList(int[] table, Product product, int V) {
List<Pack> list = new ArrayList<>();
if ( table[V] == Integer.MAX_VALUE ) return list;
while ( V > 0 ) {
for (Pack pack : product.packList) {
if ( V >= pack.qty && table[V-pack.qty] == table[V] - 1 ) {
list.add(pack);
V = V-pack.qty;
break;
}
}
}
}
For your example of V = 13 , the list would be :
[{3, 5.95}, {5, 9.95}, {5, 9.95}]
This is assuming you implement toString() of the Pack class as;
public String toString() {
return "{" + this.qty + "," + this.price + "}";
}
You can reduce your list to a map if you would like using Collectors
something like : list.stream().collect(Collectors.groupingBy(Pack::getQty))

Related

How can I generate 4 random numbers with unrepeated digits

I want to generate 4 random numbers and they can't have repeated digits.
For instance 4567, (it doesn't have a repeated value like 4557).
I want them to be random.
Is there any way to achieve this?
I'm obsessed with streams nowadays. But streams are pretty slow. To show the slowness I wrote following main method. "generateWithLoop" method covers #WJS's answer.
public static void main(String[] args) {
long nanoStart = System.nanoTime();
generateWithStreams();
long nanoEnd = System.nanoTime();
System.out.println("Elapsed time with Streams : " + (nanoEnd - nanoStart) + " nano seconds");
nanoStart = System.nanoTime();
generateWithLoop();
nanoEnd = System.nanoTime();
System.out.println("Elapsed time with Loop : " + (nanoEnd - nanoStart) + " nano seconds");
}
Console output :
Elapsed time with Streams : 81367089 nano seconds
Elapsed time with Loop : 75093 nano seconds
With stream :
public static void generateWithStreams() {
List<Integer> orderedList = getOrderedList();
for (int i = 0; i < 4; i++) {
List<Integer> shuffledList = getShuffledList(orderedList);
System.out.println(get4DigitNumber(shuffledList));
}
}
public static List<Integer> getOrderedList() {
return IntStream.range(0, 10).boxed().collect(Collectors.toList());
}
public static List<Integer> getShuffledList(List<Integer> list) {
return list.stream().sorted((o1, o2) -> ThreadLocalRandom.current().nextInt(-1, 2)).collect(Collectors.toList());
}
public static Integer get4DigitNumber(List<Integer> shuffledList) {
final Integer LIMIT = shuffledList.get(0).equals(0) ? 5 : 4;
return shuffledList.stream().limit(LIMIT).reduce(0, (sum, current) -> sum * 10 + current);
}
With loop :
public static void generateWithLoop() {
Random r = new Random();
for (int k = 0; k < 4; k++) {
int val = gen(r);
System.out.println(val);
}
}
static int[] base = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
public static int gen(Random r) {
int val = 0;
int s = 10;
for (int i = 0; i < 4; i++) {
int n = r.nextInt(s);
val = val * 10 + base[n];
int save = base[n];
base[n] = base[--s];
base[s] = save;
}
return val < 1000 ? val * 10 + base[r.nextInt(s)] : val;
}
This will generate 4 digit random numbers with no repeating digits.
It works by generating 4 unique digits in the same fashion that one might shuffle a deck of cards in a computer game. It then simply builds up the four digit number by multiplication and addition.
If the number is less than 1000, then that means a 0 was used and was at the beginning. So just choose another digit to adjust.
Random r = new Random();
for (int k = 0; k < 10; k++) {
int val = gen(r);
System.out.println(val);
}
static int[] base = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
public static int gen(Random r) {
int val = 0;
int s=10;
for (int i = 0; i < 4; i++) {
int n = r.nextInt(s);
val = val * 10 + base[n];
int save = base[n];
base[n] = base[--s];
base[s] = save;
}
return val < 1000 ? val * 10 + base[r.nextInt(s)] : val;
}
Here is a more straightforward way of doing it. The philosophy is the same as above. It may not be quite as efficient as the previous due to the shuffling of all the digits.
// generate four digit numbers that have distinct digits.
List<Integer> digits = Arrays.asList(0,1,2,3,4,5,6,7,8,9);
Collections.shuffle(digits);
// now just use the first four of the shuffled list
if (digits.get(0) == 0) {
// for a 4 digit number, first digit can't be zero
// so choose another.
digits.set(0, digits.get(4));
}
// now use simple arithmetic to create the four digit number.
int n = 0;
for (int d : digits.subList(0,4)) {
n = n * 10 + d;
}
System.out.println(n);
public static void main(String[] args) {
List<Integer> list= new ArrayList<>();
for(int j = 0; j < 10; j++){
list.add(j);
}
Collections.shuffle(list);
String randomDigit= "";
for(int j = 0; j < 4; j++){
randomDigit+= list.get(j).toString();
}
System.out.println(randomDigit);
}
This is converting the string to int. But this will work you can use it.
Steps:
Create a List that will hold each individual number of the generated
4-digit number
Generate a random number for the units place between 1 and 9, and put it in the list
Create a loop to generate a random number between 0 and 9 for the
ten's place until the last place; and each time, put the random
number into your list. examine the number for each iteration that is not contained in your list
Eventually the size of the list is now 4; combine these 4 individuals into a String, and convert to Integer.
List<Integer> myNumber = new ArrayList<Integer>();
Random r = new Random();
// Generate a random number between 1 and 9 for units place
myNumber.add(r.nextInt(9) + 1);// adding 1 to avoid 0 in the units place
// Generate a random number between 0 and 9 for 10's and upcoming places
do {
Integer num = r.nextInt(10);
// Check the list doesn't contain that number
if (!myNumber.contains(num)) {
myNumber.add(num);
}
}while (myNumber.size() < 4);
StringBuilder numStr = new StringBuilder();
for (int i = 0; i < myNumber.size(); i++)
numStr.append(myNumber.get(i));
System.out.println(Integer.parseInt(numStr.toString()));
A solution using stream and Lambdas from Java-8 onwards:
public static void main(String[] args) {
Map<String, String> collect = IntStream.rangeClosed(1, 9).boxed()
.flatMap(x -> IntStream.rangeClosed(0, 9).boxed()
.flatMap(y -> IntStream.rangeClosed(0, 9).boxed()
.flatMap(z -> IntStream.rangeClosed(0, 9).boxed()
.flatMap(w -> IntStream.rangeClosed(1, 9).boxed().map(s -> s.toString()).filter(e -> noneRepete(x, y, z, w))
.map(k -> x.toString() + y.toString() + z.toString() + w.toString())))))
.collect(Collectors.toMap(Function.identity(), s -> s, (a, b) -> a));
collect.keySet().forEach(System.out::println);
}
public static boolean noneRepete(Integer a, Integer b, Integer c, Integer d) {
if (! a.equals(b) && ! a.equals(c) && ! a.equals(d) && a !=0) {
if (! b.equals(c) && ! b.equals(d)) {
return ! c.equals(d);
}
}
return false;
}
Explanation:
Here we are flattening the stream of Integers from 1 to 9(first digit cannot be 0).
while in further we are flattening stream of Integers from 0 to 9.
The above process goes 2 more time thus making it a four digit, we are having a custom filter which is making sure that all four digits are unique.
At last we are collecting them as keys and values making sure the digits are unique and key itself in a map is unique.

choose a random value from a inverse weigthed map

I'm using a Map with eligible words for a hangman game I'm developing. The Integer in the Map stores the times a word has been chosen, so in the beginning the Map looks like this:
alabanza 0
esperanza 0
comunal 0
aprender 0
....
After some plays, the Map would look like this
alabanza 3
esperanza 4
comunal 3
aprender 1
....
I'd like to choose the next word randomly but having the less chosen word a bigger probability of been chosen.
I've read Java - Choose a random value from a HashMap but one with the highest integer assigned but it's the opposite case.
I''ve also thought I could use a list with repeated words (the more times a word appears in the list, the more the probabilities of been chosen) but I've only managed to get to this:
int numberOfWords=wordList.size(); //The Map
List<String> repeatedWords=new ArrayList<>();
for (Map.Entry<String,Integer> entry : wordList.entrySet()) {
for (int i = 0; i < numberOfWords-entry.getValue(); i++) {
repeatedWords.add(entry.getKey());
}
}
Collections.shuffle(repeatedWords); //Should it be get(Random)?
String chosenWord=repeatedWords.get(0);
I think this fails when the amount of words chosen equals the amount of words.
Edit
Finally there's a problem with the probability of each word once they have different numbers. I've changed the point of view so I first put a probability of 1000 (It could be any number) and every time I choose a word, I reduce the probability a certain amount (let's say, 20%), so I use:
wordList.put(chosen,(int)(wordList.get(chosen)*0.8)+1);
After that I choose the word with the recipe Lajos Arpad or Ahmad Shahwan gave.
If the game were to be played many many times, all the probabilities would tend to 1, but that's not my case.
Thanks all who answered.
Try this:
import java.util.Map;
import java.util.HashMap;
import java.util.Random;
public class MyClass {
public static void main(String args[]) {
Map<String, Integer> wordList = new HashMap<>();
wordList.put("alabanza", 3);
wordList.put("esperanza", 4);
wordList.put("comunal", 3);
wordList.put("aprender", 1);
Map<String, Integer> results = new HashMap<>(4);
for (int i = 0; i < 100; i++) {
String name = randomize(wordList);
Integer old = results.getOrDefault(name, 0);
results.put(name, old + 1);
}
for (Map.Entry<String, Integer> e : results.entrySet()) {
System.out.println(e.getKey() + "\t" + e.getValue());
}
}
private static String randomize(Map<String, Integer> wordList) {
final Integer sum = wordList.values().stream().reduce(Integer::sum).orElse(0);
final int grandSum = (wordList.size() - 1) * sum;
final int random = new Random().nextInt(grandSum + 1);
int index = 0;
for (Map.Entry<String, Integer> e: wordList.entrySet()) {
index += (sum - e.getValue());
if (index >= random) {
return e.getKey();
}
}
return null;
}
}
Out put is the times a name was chosen over 100 trial:
aprender 37
alabanza 25
comunal 23
esperanza 15
You can try it yourself here.
I won't provide exact code, but basic idea.
Iterate over wordList.values() to find the maximum weight M and sum of weights S.
Now let each word w have likelihood (like probability, but they don't have to sum to 1) to be chosen M + 1 - wordList.get(w), so a word with weight 1 is M times more likely to be chosen than a word with weight M.
The sum of likelihoods will be (M + 1) * wordList.size() - S (that's why we need S). Pick a random number R between 0 and this sum.
Iterate over wordList.entrySet(), summing likelihoods as you go. When the sum passes R, that's the word you want.
Your map values are your weights.
You need to pick an integer lower than the weights sum.
You pick each String entry, with its weight. When the weight sum passes the random integer, you are on THE String.
This will give you :
public static void main(String ... args){
Map<String, Integer> wordList = new HashMap<>();
wordList.put("foo", 4);
wordList.put("foo2", 2);
wordList.put("foo3", 7);
System.out.println(randomWithWeight(wordList));
}
public static String randomWithWeight(Map<String, Integer> weightedWordList) {
int sum = weightedWordList.values().stream().collect(Collectors.summingInt(Integer::intValue));
int random = new Random().nextInt(sum);
int i = 0;
for (Map.Entry<String, Integer> e : weightedWordList.entrySet()){
i += e.getValue();
if (i > random){
return e.getKey();
}
}
return null;
}
For the sake of simplicity let us suppose that you have an array called occurrences, which has int elements (you will easily translate this into your data structure).
Now, let's find the maximum value:
int max = 0;
for (int i = 0; i < occurrences.length; i++) {
if (max < occurrences[i]) max = occurrences[i];
}
Let's increment it:
max++;
Now, let's give a weight of max to the items which have 0 as value, a weight of max - 1 to the items which occurred once, and so on (no item will have a weight of 0 since we incremented max):
int totalWeight = 0;
for (int j = 0; j < occurrences.length; j++) {
totalWeight += max - occurrences[j];
}
Note that all items will have their weight. Now, let's suppose you have a randomized integer, called r, where 0 < r <= totalWeight:
int resultIndex = -1;
for (int k = 0; (resultIndex < 0) && k < occurrences.length; k++) {
if (r <= max - occurrences[k]) resultIndex = k;
else r -= max - occurrences[k];
}
and the result is occurrences[resultIndex]

Restaurant Maximum Profit using Dynamic Programming

Its an assignment task,I have spend 2 days to come up with a solution but still having lots of confusion,however here I need to make few points clear. Following is the problem:
Yuckdonald’s is considering opening a series of restaurant along QVH. n possible locations are along a straight line and the distances of these locations from the start of QVH are in miles and in increasing order m1, m2, ...., mn. The constraints are as follows:
1. At each location, Yuckdonald may open one restaurant and expected profit from opening a restaurant at location i is given as pi
2. Any two restaurants should be at least k miles apart, where k is a positive integer
My solution:
public class RestaurantProblem {
int[] Profit;
int[] P;
int[] L;
int k;
public RestaurantProblem(int[] L , int[] P, int k) {
this.L = L;
this.P = P;
this.k = k;
Profit = new int[L.length];
}
public int compute(int i){
if(i==0)
return 0;
Profit[i]= P[i]+(L[i]-L[i-1]< k ? 0:compute(i-1));//if condition satisfies then adding previous otherwise zero
if (Profit[i]<compute(i-1)){
Profit[i] = compute(i-1);
}
return Profit[i];
}
public static void main(String args[]){
int[] m = {0,5,10,15,19,25,28,29};
int[] p = {0,10,4,61,21,13,19,15};
int k = 5;
RestaurantProblem rp = new RestaurantProblem(m, p ,k);
rp.compute(m.length-1);
for(int n : rp.Profit)
System.out.println(n);
}
}
This solution giving me 88 however if I exclude (Restaurant at 25 with Profit 13) and include (Restaurant 28 with profit 19) I can have 94 max...
point me if I am wrong or how can I achieve this if its true.
I was able to identify 2 mistakes:
You are not actually using dynamic programming
, you are just storing the results in a data structure, which wouldn't be that bad for performance if the program worked the way you have written it and if you did only 1 recursive call.
However you do at least 2 recursive calls. Therefore the program runs in Ω(2^n) instead of O(n).
Dynamic programming usually works like this (pseudocode):
calculate(input) {
if (value already calculated for input)
return previously calculated value
else
calculate and store value for input and return result
}
You could do this by initializing the array elements to -1 (or 0 if all profits are positive):
Profit = new int[L.length];
Arrays.fill(Profit, -1); // no need to do this, if you are using 0
public int compute(int i) {
if (Profit[i] >= 0) { // modify the check, if you're using 0 for non-calculated values
// reuse already calculated value
return Profit[i];
}
...
You assume the previous restaurant can only be build at the previous position
Profit[i] = P[i] + (L[i]-L[i-1]< k ? 0 : compute(i-1));
^
Just ignores all positions before i-1
Instead you should use the profit for the last position that is at least k miles away.
Example
k = 3
L 1 2 3 ... 100
P 5 5 5 ... 5
here L[i] - L[i-1] < k is true for all i and therefore the result will just be P[99] = 5 but it should be 34 * 5 = 170.
int[] lastPos;
public RestaurantProblem(int[] L, int[] P, int k) {
this.L = L;
this.P = P;
this.k = k;
Profit = new int[L.length];
lastPos = new int[L.length];
Arrays.fill(lastPos, -2);
Arrays.fill(Profit, -1);
}
public int computeLastPos(int i) {
if (i < 0) {
return -1;
}
if (lastPos[i] >= -1) {
return lastPos[i];
}
int max = L[i] - k;
int lastLastPos = computeLastPos(i - 1), temp;
while ((temp = lastLastPos + 1) < i && L[temp] <= max) {
lastLastPos++;
}
return lastPos[i] = lastLastPos;
}
public int compute(int i) {
if (i < 0) {
// no restaurants can be build before pos 0
return 0;
}
if (Profit[i] >= 0) { // modify the check, if you're using 0 for non-calculated values
// reuse already calculated value
return Profit[i];
}
int profitNoRestaurant = compute(i - 1);
if (P[i] <= 0) {
// no profit can be gained by building this restaurant
return Profit[i] = profitNoRestaurant;
}
return Profit[i] = Math.max(profitNoRestaurant, P[i] + compute(computeLastPos(i)));
}
To my understanding, the prolem can be modelled with a two-dimensional state space, which I don't find in the presented implementation. For each (i,j) in{0,...,n-1}times{0,...,n-1}` let
profit(i,j) := the maximum profit attainable for selecting locations
from {0,...,i} where the farthest location selected is
no further than at position j
(or minus infinity if no such solution exist)
and note that the recurrence relation
profit(i,j) = min{ p[i] + profit(i-1,lastpos(i)),
profit(i-1,j)
}
where lastpos(i) is the location which is farthest from the start, but no closer than k to position i; the first case above corresponds to selection location i into the solution while the second case corresponds to omitting location j in the solution. The overall solution can be obtained by evaluating profit(n-1,n-1); the evaluation can be done either recursively or by filling a two-dimensional array in a bottom-up manner and returning its contents at (n-1,n-1).

How to find the biggest three numbers in an array java?

I have an array of numbers and I need the biggest of three number with respective index value. I have an array like this:
int [] value = new int[5];
value[0] = 8;
value[1] = 3;
value[2] = 5;
value[3] = 2;
value[4] = 7;
How to find the largest numbers and their index values?
I suspsect this is homework, so I'm going to give some help, but not a full solution.
You need the biggest three numbers, as well as their index values?
Well, walk over the array, keeping track of the highest three numbers you have found so far. Also keep track of their index numbers.
You could start by doing this for only the biggest number and its index. That should be easy.
It takes two variables, e.g. BiggestNumber and indexOfBiggestNumber. Start with finding the biggest number (trivial), then add some code to remember it's index.
Once you have that, you can add some more code to keep track of the second biggest number and it's index as well.
After that, you do the same for the third biggest number.
I have done it for you, and this works.
here goes the complete code:
import java.util.Arrays;
class tester {
public static void main(String[] args) {
int[] value = new int[5];
value[0] = 8;
value[1] = 3;
value[2] = 5;
value[3] = 2;
value[4] = 7;
int size = value.length;
int[] temp = (int[]) value.clone();
Arrays.sort(temp);
for (int i = 0; i < 3; i++) {
System.out.println("value: " + temp[size - (i + 1)] +
" index " + getIndex(value, temp[size - (i + 1)]));
}
}
static int getIndex(int[] value, int v) {
int temp = 0;
for (int i = 0; i < value.length; i++) {
if (value[i] == v) {
temp = i;
break;
}
}
return temp;
}
}
No need to traverse through array and keep tracking of so many variables , you can take advantage of already implemented methods like below.
I would suggest to use a List of Map.Entry<key,value > (where key=index and value=number) and then implement Comparator interface with overridden compare method (to sort on values). Once you have implemented it just sort the list .
public static void main(String[] args) {
int[] value = {5, 3, 12, 12, 7};
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int k = 0; k < value.length; k++)
map.put(k, value[k]);
List<Map.Entry<Integer, Integer>> list =
new LinkedList<Map.Entry<Integer, Integer>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
#Override
public int compare(
Entry<Integer, Integer> e1,
Entry<Integer, Integer> e2) {
return e2.getValue().compareTo(e1.getValue());
}
});
for (Entry<Integer, Integer> lValue : list)
System.out.println("value = " + lValue.getValue()
+ " , Index = " + lValue.getKey());
}
Results:
value = 12 , Index = 2
value = 12 , Index = 3
value = 7 , Index = 4
value = 5 , Index = 0
value = 3 , Index = 1
By this approach you can get top N largest numbers with their index.
To get the three biggest, basically, you sort, and pick the last three entries.
Getting their indexes takes a little more work, but is definitely doable. Simply bundle the number and its index together in a Comparable whose compareTo function only cares about the number. Sort, get the last three items, and now you have each number and its index.
class IntWithIndex implements Comparable<IntWithIndex> {
public int number, index;
public IntWithIndex(number, index) {
this.number = number;
this.index = index;
}
public int compareTo(IntWithIndex other) {
return number - other.number;
}
}
...
IntWithIndex iwi[] = new IntWithIndex[yourNumbers.length];
for (int i = 0; i < yourNumbers.length; ++i) {
iwi[i] = new IntWithIndex(yourNumbers[i], i);
}
Arrays.sort(iwi);
int largest = iwi[iwi.length - 1].number;
int largestIndex = iwi[iwi.length - 1].index;
// and so on
Sort the array in descending order and show the first 3 element.

Permutation - Need help desining a better block that won't need unused values

I need help making my permutation's (order important, repeatable) size smaller by discarding the unneeded permutations before hand.
The current permutation takes a global minimum and maximum from the values provided. However, some of the permutations are discarded afterward as they don't fall within the range needed.
The idea is there are for example 3 numbers which need a permutation. For example: 1-3, 8-10 and 5-15. The current code will create a permutation of 1-15 even though values from 4-7 will be discarded later on.
Unfortunately in some instances its not possible to create an array large enough in Java to contain the permutation results.
Any help would be appreciated on changing this permutation to only include necessary values prior to computing the permutation.
PermutationCore:
public class PermutationCore {
private String[] a;
private int n;
public PermutationCore(String[] arrayOfPossibilities, int lengthOfPermutation) {
this.a = arrayOfPossibilities;
this.n = lengthOfPermutation;
}
public String[][] getVariations() {
int l = a.length;
int permutations = (int) Math.pow(l, n);
Co.println("Permutation array size: " + permutations);
String[][] table = new String[permutations][n];
for (int x = 0; x < n; x++) {
int t2 = (int) Math.pow(l, x);
for (int p1 = 0; p1 < permutations;) {
for (int al = 0; al < l; al++) {
for (int p2 = 0; p2 < t2; p2++) {
table[p1][x] = a[al];
p1++;
}
}
}
}
return table;
}
}
Permutation
public class Permutation {
private ArrayList<Iteration> listOfIteration = new ArrayList<Iteration>();
private boolean prepared;
private PermutationCore permutationCore;
private int min = Integer.MAX_VALUE;
private int max = Integer.MIN_VALUE;
private int count = 0;
private String[][] arrayOfStringResults;
public void addIteration(Iteration iteration){
if (prepared){throw new IllegalStateException("Permuation is already prepared. Create a new instance to add new items");}
this.listOfIteration.add(iteration);
}
public void prepare(){
String[] arrayOfString;
for (Iteration iteration : listOfIteration){
if (iteration.end > max){max = iteration.end;}
if (iteration.start < min){min = iteration.start;}
}
arrayOfString = new String[max-min+1];
for (int i=0; i<arrayOfString.length; i++){
arrayOfString[i] = String.valueOf(min+i);
}
permutationCore = new PermutationCore(arrayOfString, listOfIteration.size());
prepared = true;
// Co.println("Min/max: " + min + "," + max);
arrayOfStringResults = permutationCore.getVariations();
// ArrayTools.sort2DStringArray(arrayOfStringResults);
}
public boolean iterate(){
LABEL_ITERATE_LOOP: {
int i=0;
if (count == arrayOfStringResults.length){
return false;
}
for (Iteration iteration : listOfIteration){
int currentValue = Integer.valueOf(arrayOfStringResults[count][i]);
if (currentValue > iteration.end || currentValue < iteration.start){
//Co.println("Failed at: " + iteration.start + "," + iteration.end + " / " + currentValue);
count++;
break LABEL_ITERATE_LOOP;
}
iteration.current = currentValue;
i++;
}
count++;
}
return true;
}
public Iteration getIteration(Object request) {
for (Iteration iteration : listOfIteration){
if (iteration.request == request){
return iteration;
}
}
return null;
}
public ArrayList<Iteration> getListOfIterations(){
return listOfIteration;
}
public static class Iteration{
private int start;
private int end;
private int current;
private Object request;
public Iteration(int start, int end, Object request){
this.start = start;
this.end = end;
this.request = request;
}
public double getCurrentValue(){
return this.current;
}
public Object getRequest(){
return this.request;
}
}
}
This of your problem as permuting k numbers from 0 to (n-1), and printing a[n] instead of n. :) That is what you can do, to reduce iterations.
The other way to do it, is to use a number between 0 to n!-1 and figure out what the current permutation is, and print it. Although it is a slower method, it's faster to resume operations in this format - and we can quickly print the kth permutation.
Let us say the numbers are: 1, 2, 3, 4. There are a total of 4! permutation = 24, possible. To print the 15th (counting from zero) permutation, here's what we do:
n = 4
a = 1 2 3 4
divide 15 by (n-1)!
we get 15/6 = 2, reminder = 3.
So the permutation starts with a[2] = 3.
a = 1 2 4
take the reminder, divide by (n-2)!
we get 3/2 = 1, reminder = 1.
so the permutation is now permutation, a[1] = 3, 2
a = 1 4
take the reminder, divide by (n-1)!
we get 1/1 = 1, reminder = 0
so the permutation is now permutation, a[1] = 3, 2, 4.
do until reminder is zero. print a[0]= 3, 2, 4, 1.
^ this is the most efficient way to generate the kth permutation of any series.
You can use BigInteger math to perform this method very efficiently.

Categories

Resources