简体   繁体   中英

How to encode N strings to binary numbers with minimum number of digits

I have a list of names, ArrayList<String> names . For example:

ArrayList<String> names= new ArrayList<String>();
names.add("foo1"); 
names.add("foo2");
names.add("foo3");
names.add("foo4");
names.add("foo5");

Then I can encode these five names into binary numbers with (ceiling(log(5))=) 3 digits: foo1=000, foo2=001, foo3=010, foo4=011, foo5=100 . I want a function which looks like public int[] return_binary_encoding(String name, ArrayList<String> names) , where name is in names .

Thanks to all who helped me with their comments.

    public int[] return_binary_encoding(String name, ArrayList<String> names) {

    int code[];
    int domain_size= names.size();
    int siz_of_code= (int)Math.ceil(Math.log(domain_size)/Math.log(2));
    code= new int[siz_of_code];     //it is initialized to 0 by default

    int index= names.indexOf(name);
    String binary_code= Integer.toBinaryString(index);

    //insert binary_code in code from right
    int counter= code.length - 1;
    for(int i= binary_code.length()-1; i>= 0; i--) {
        int digit= Character.getNumericValue(binary_code.charAt(i));
        code[counter]= digit;
        counter --;
    }


    return code;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM