전단사함수(Bijection) 알고리즘

2024-04-02 20:10 | Java

Java 전단사함수 구현하기

전단사함수(Bijection) 알고리즘. 숫자만으로 구성된 일련번호를 대/소문자와 숫자의 조합으로 변경

전단사함수 구현

public class Bijection {
 
    private static String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static int base = alphabet.length();
 
 
    public static String encode(int num){
        String encoded = "";
        while (0 < num){
            int remainder = num % base;
            num = (int)Math.floor(num / base);
            encoded = alphabet.charAt(remainder) + encoded;
         }
        return encoded;
    }
 
    public static int decode(String str){
        int decoded = 0;
        while (0 < str.length()){
          int index = alphabet.indexOf(str.charAt(0));
          int power = str.length() - 1;
          decoded += index * (Math.pow(base, power));
          str = str.substring(1);
          
        }
        return decoded;
    }
 
}
 
 

전단사함수 사용

 
public static void main(String args[]) {
 
  int code=Bijection.encode(100000028);
 
  System.out.println(code);
 
}