Calculate the unrank of of permutaion:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Collection; | |
import java.util.Collections; | |
import java.util.LinkedList; | |
import java.util.List; | |
import java.util.stream.Collectors; | |
public class unrank { | |
public static int factorial(int number){ | |
if (number == 1 || number==0) | |
return 1; | |
return number * factorial(number-1); | |
} | |
public static String calculateUnrank(String test, int unranknum) { | |
List<Character> answer = new LinkedList<>(); | |
List<Character> lst = new LinkedList<Character>(); | |
for (char a : test.toCharArray()) { | |
lst.add(a); | |
} | |
Collections.sort(lst); | |
while (lst.size() != 0) { | |
int totalPermutation = factorial(lst.size()); | |
int eachblock = totalPermutation / lst.size(); | |
int dividend = unranknum / eachblock; | |
unranknum = unranknum % eachblock; | |
char value = lst.get(dividend); | |
answer.add(Character.valueOf(value)); | |
lst.remove(Character.valueOf(value)); | |
} | |
return answer.stream().map(String::valueOf).collect(Collectors.joining()); | |
} | |
public static void main (String args[]){ | |
String test = "SPAIN"; | |
int unranknum = 115; | |
String result = calculateUnrank(test,unranknum); | |
System.out.println(result); | |
} | |
} |
No comments:
Post a Comment