简体   繁体   English

如何将N个字符串编码为具有最小位数的二进制数

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

I have a list of names, ArrayList<String> 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 . 然后,我可以使用(ceiling(log(5))=)3位数字将这五个名称编码为二进制数字: 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 . 我想要一个看起来像public int[] return_binary_encoding(String name, ArrayList<String> names)的函数,其中namenames

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从两个 n 位二进制数创建一个 2n 位二进制数? - How can i create from two n-bit binary numbers a 2n-binary number? 如何在JAVA中编码为4位数字或数字字符串? - How to encode TO a 4 digits number or nummerical string in JAVA? 我如何获得最小数量的ArrayList <Integer> 需要具有从1到“ n”的所有数字吗? - how I can get the minimum number of ArrayList<Integer> needed to have all numbers from 1 to “n”? 如何计算电话号码的位数? - how count the number of digits of telephone numbers? 打印数字的二进制数字 - Printing binary digits of a number 给定数字n,列出所有n位数字,使得每个数字不具有重复数字 - Given a number n, list all n-digit numbers such that each number does not have repeating digits 在数字上添加数字 - Adding numbers digits to number 计算小于或等于N的两个数字的对数,以使对数的数字总和为质数 - Count number of pairs of two numbers less than or equal to N such that Sum of the digits of numbers of pair is Prime 如何排列数字的数字,以便当我将其分成两个相同数字的数字时,两个数字的乘积最大? - How to arrange the digits of a number such that when I break it into two numbers of equal digits the product of the two numbers is maximum? 指定位数后如何计算二进制数? - How do I count in binary after specifying a given number of digits?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM