0

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.

8
  • 1
    So you want a number tied to the string... For your system all data is in binary, so your 000, 001, 010, 011, 100 are literally 0, 1, 2, 3, 4... Isn't that the index value of your strings in the ArrayList? Commented Mar 18, 2016 at 3:45
  • What is String name? What is its significance in the question you asked? Have you tried anything - some lines of code? Commented Mar 18, 2016 at 3:52
  • name is in the names. Ok, now I feel this was a stupid question since I can get the index of name by names.indexOf(name) and then I just need to convert it to a binary number with log(k) digits. right? Commented Mar 18, 2016 at 3:58
  • @Prashnant @OliPro007 based on what you said, I think the following will do almost the job: Integer.toBinaryString(names.indexOf(name)) and then I just need to add enough 0s to have a binary number with log(k) digits. right? Commented Mar 18, 2016 at 4:04
  • 1
    @Reza Seems like it, this post may help you do that. Commented Mar 18, 2016 at 4:07

1 Answer 1

0

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.