Java putting all permutations of an Int array into another array without repeats -
there many other questions on stack overflow this, 1 asks different others. want know how take permutations of int array, without repeats, , put them in 2d array. example, input: {1,2,3}
output:
{1,2,3} {1,3,2} {2,1,3} {2,3,1} {3,1,2} {3,2,1}
how can accomplish this? i'd verbal walk through on how this, or better code. question differs this one because linked 1 uses c++ functions accomplish this. use java.
thanks
java object-oriented language , believe useful consider objects problem might contain.
one thing jumps out of problem domain triple-set of integers, why not define object:
public class triad { private final int[] components; public triad(int... numbers) { this.components = numbers; if (components.length != 3) throw new illegalargumentexception(); } @override public boolean equals(object ob) { if (ob == this) return true; if (!(ob instanceof triad)) return false; triad test = (triad) ob; return arrays.equals(this.components, test.components); } @override public int hashcode() { return arrays.hashcode(this.components); } }
note triad
defines equals()
method , hashcode()
method. important couple of reasons. triad
value class, i.e. instances of triad
represent values rather active. value classes typically:
- should immutable (as have defined triad far, immutable)
- have well-formed equals() , hashcode() methods
the last property above allows instances used without fear java collections framework. let's put collections framework use:
public static void main(string[] args) { set<triad> triads = new hashset<triad>(); triad inputtriad; while (true) { int[] numbers = ... // read in data source if (numbers == null) break; inputtriad = new triad(numbers); triads.add(inputtriad); } // after loop has completed, hashset instance triad contain // input triads. contract of hashset guarantees there // no duplicates. : : }
if must have result in int arrays, simple matter iterate through hashset instance , assign component values of each element result arrays.
Comments
Post a Comment