For months without the code, get a demo of the combo today.
The idea is to compare each value of the collection to an index, which is the size of the collection +2. The index defaults to [000...000], and when combined, the selected combined value is [0100..00]. It then takes a value from the collection according to the traversal index.
On the code:
Importjava.util.ArrayList;ImportJava.util.Iterator;Importjava.util.List; Public classCombit { Public Static voidMain (string[] args) {//Integer Test int[] combination =New int[] {1, 2, 3, 4 }; List<Integer> combinationlist =NewArraylist<integer>(); for(integer integer:combination) {combinationlist.add (integer); } combititerator<Integer> i =NewCombititerator<integer>(combinationlist); while(I.hasnext ()) {Object obj=I.next (); System.out.println (Obj.tostring ()); } //String Teststring[] str =NewString[] {"Apple", "orange", "tomato", "potato" }; List<String> combinationslist =NewArraylist<string>(); for(String s:str) {Combinationslist.add (s); } combititerator<String> II =NewCombititerator<string>(combinationslist); while(Ii.hasnext ()) {Object obj=Ii.next (); System.out.println (Obj.tostring ()); } }}classCombititerator<t>ImplementsIterator<t> { Private int[] _bitarray =NULL; protected Final int_length; protected FinalList<t>combination; protectedList<t>_currentset; PublicCombititerator (list<t>combination) {_currentset=NewArraylist<t>(); This. _length =combination.size (); This. _bitarray =New int[_length + 2]; This. Combination =combination; } @Override Public BooleanHasnext () {return_bitarray[_length + 1]! = 1; } @SuppressWarnings ("Unchecked") @Override PublicT Next () {_currentset.clear (); for(intindex = 1; Index <= _length; index++) { if(_bitarray[index] = = 1) {T value= Combination.get (index-1); _currentset.add (value); } } inti = 1; while(_bitarray[i] = = 1) {_bitarray[i]= 0; I++; } _bitarray[i]= 1; return(T) _currentset; }}
------------------------------------------------Split Line---------------------------------------------------------
PS: code from the requirements of the number 1-20 in the combination of any n to the value of 36, so thinking of two, the first is recursion, the second is recursive, but want to get a generic, there is the above code. In addition, someone in the group wrote the code of direct recursion, also attached:
Public Static voidMain (string[] args) {Combinatedataofrange (1, 20, 36); } Public Static voidCombinatedataofrange (intMinintMaxinttarget) {Combinatedata (0, Min, max, Target,NewStack<integer>()); } Public Static voidCombinatedata (intSumintMinintMaxintTarget, Stack<Integer>stack) { for(inti = Stack.isempty ()? Min: (Integer) stack.lastelement () + 1; i < Max; ++i) {intTempSum = sum +i; Stack.push (i); if(TempSum = =target) {System.out.println (Stack+ "=" +target); } Else{combinatedata (tempsum, Min, max, target, stack); } stack.pop (); } }
Java to find a combination in a collection