Rearranging numbers combination
in
Programming Questions
•
6 months ago
Hi i wanted to rearrange numbers with every possible combinations,
for example:
i key in 123 and i want to find every other possible combination from this number like
132
213
231
312
321
below are my code and i'm able to do it, but sometimes it doesn't works, and is there a much more simple way to do it? i believe there is much simple code than mine.
-
ArrayList<String> combinations = new ArrayList<String>();
class n {int number;boolean used;
n(int x) {number = x;used = false;}}
int counter = 0;
n[] num = new n[4]; // 4 means 4 digit number like 8134 which have 24 combinationString com = "";for (int i = 0 ; i != num.length; i++) {num[i] = new n(round(random(9)));com += num[i].number;}combinations.add(com);com = "";
int rounds = 0;while ( rounds != 23 ) { //23 means the number of possible combinationfor (int i = 0 ; i != num.length; i++) {int rand = round(random(num.length-1));while (num[rand].used) {rand = round(random(num.length-1));}com += num[rand].number;num[rand].used = true;}for (int i = 0 ; i != num.length; i++) {num[i].used = false;}for (int i = 0 ; i != combinations.size(); i++) {if (int(com) == int(combinations.get(i))) {counter += 1;}}if (counter == 0) {combinations.add(com);com = "";rounds+=1;}else{com = "";}counter = 0;}println(combinations);
1