Put the input digits in the list, create a random generator that will return the indices of this list, will form your output:
Integer input = 5278; char[] digits = String.valueOf(input).toCharArray(); int numberOfTrinities = 4; String result = ""; Random generator = new Random(); List<String> trinities = new ArrayList<String>(); while(trinities.size() < numberOfTrinities ) { String nextTrinity = ""; for(int i = 0; i < 3; i++) { nextTrinity += digits(generator.nextInt(digits.size())); } if(isUniqueDigitsTrinity(trinities, nextTrinity)) { trinities.add(nextTrinity); } } String result = ""; for(String trinity : trinities) { result += trinity; } System.out.printl("Input: " + input + ", Result: " + result);
We do not check the unique numbers in the trinity:
private boolean isUniqueDigitsTrinity(List<String> trinities, String candidateTrinity) { for(String existingTrinity : trinities) { String checker = existingTrinity; for(char candidateChar : candidateTrinity.toCharArray()) { checker.replace(candidateChar, ''); } if(checker.length() <= 0) { return false; } } return true; }
source share