[Week Four] Programming Contest - Binary Strings

Welcome back to week four of the weekly programming contests! As always, you can find the rules and information on the contests Posted Here

This weeks challenge is a relatively simpler one. Your job is to implement the method: public static String binary(String s) (THE METHOD NAME CANNOT BE RENAMED). Here’s what the method does in a list of steps:

  1. Converts each of the characters in the s String to their corresponding ASCII code (“Hi” -> 72 105)
  2. Converts all of the ASCII codes to binary (72 105 -> 1001000 1101001)
  3. Inverts the resulting Binary Strings (1001000 1101001 -> 0110111 0010110)
  4. And finally returns everything slapped together as one big String (0110111 0010110 -> “01101110010110”)

Your code doesn’t have to follow these steps exactly. Any implementation which yields the expected result is fine.

As always, here are your complementary examples:

binary(“Hello!”) -> 01101110011010001001100100110010000011110
binary(“The”) -> 010101100101110011010
binary(“chickens”) -> 00111000010111001011000111000010100001101000100010001100
binary(“eat”) -> 001101000111100001011
binary(“happy”) -> 00101110011110000111100011110000110
binary(“pickles!”) -> 0001111001011000111000010100001001100110100001100011110

Imports are allowed for this challenge!

Challenge Closes: Sunday 11/29/15

Good luck!

213 Characters:

public static String binary(String s)throws UnsupportedEncodingException{String r="";for(byte b:s.getBytes("ASCII")){r+=Integer.toBinaryString(b&0xFF);}return r.replace('0','2').replace('1','0').replace('2','1');}

Readable Version:

public static String binary(String s) throws UnsupportedEncodingException {
    String r = "";
    for (byte b : s.getBytes("ASCII")) {
        r += Integer.toBinaryString(b & 0xFF);
    }
    return r.replace('0', '2').replace('1', '0').replace('2', '1');
}
1 Like

175 characters:

public static String binary(String a){String b="";for(char c:a.toCharArray()){String d="";for(int e=128;e>0;e/=2)d+=((c%=e*2)/e+1)%2;b+=d.substring(d.indexOf("0"));}return b;}

Readable version:

public static String binary(String a) {
    String b = "";
    for (char c : a.toCharArray()) {
        String d = "";
        for (int e = 128; e > 0; e /= 2) {
            d+=((c%=e*2)/e+1)%2;
        }
        b += d.substring(d.indexOf("0"));
    }
    return b;
}

Behold the beauty that is streams.

140 134 chars

public static String binary(String s){return s.chars().mapToObj(i->Integer.toString(~i&255,2).split("^1+")[1]).reduce("",(t,u)->t+u);}

Longified


    public static String binary(String s) {
        // Int stream representing the chars
        return s.chars()
                // Flip bits of int, zero out everything all but the last byte. 
                //Then get a binary string
                .mapToObj(i -> Integer.toString(~i & 0xFF, 2)
                        // Remove leading 1s as they are not needed
                        // Since ASCII only uses 7 bit, the 8th is always 0, so
                        // the flipped string always starts with one or more
                        // 1s, thus no Out of Bound errors occur for this
                        .split("^1+")[1])
                // join the strings one by one
                .reduce("", (t, u) -> t + u);
    }

[spoiler=Original Version]
140 chars

public static String binary(String s){return s.chars().mapToObj(i->Integer.toString(~i&0xFF,2).replaceAll("^1+","")).reduce("",(t,u)->t+u);}

Longified


    public static String binary(String s) {
        // Int stream representing the chars
        return s.chars()
                // Flip bits of int, zero out everything all but the last byte. 
                //Then get a binary string
                .mapToObj(i -> Integer.toString(~i & 0xFF, 2)
                        // Remove leading 1s as they are not needed
                        .replaceAll("^1+", ""))
                // join the strings one by one
                .reduce("", (t, u) -> t + u);
    }

[/spoiler]

2 Likes

Try Integer.toString(b&0xFF,2), it will save you a whooping 4 chars :smiley:

127 characters

public static String binary(String s){String t="";for(int c:s.toCharArray())for(int i=64;i>0;i/=2)t+=(c&i)>0?"0":"1";return t;}
public static String binary(String s) {
    String t = "";
    for (int c : s.toCharArray())
        for (int i = 64; i > 0; i /= 2)
            t += (c & i) > 0 ? "0" : "1";
    return t;
}

Here’s a little template in which to test your method. Just plop in your method, compile, and run.

Code ```java public class BinaryTest { // binary(String) goes here
public static void printTestBinary(String s, String expected) {
    String actual = null;

    try {
        actual = binary(s);
    } catch (RuntimeException e) {
        System.out.printf("binary(\"%s\") threw %s:%n", s, e);
        e.printStackTrace();
        return;
    }

    System.out.printf("binary(\"%s\") returned \"%s\" %s= \"%s\"%n",
            s, actual, actual.equals(expected) ? "=" : "!", expected);
}

public static void main(String[] args) {
    printTestBinary("Hello!",   "01101110011010001001100100110010000011110");
    printTestBinary("The",      "010101100101110011010");
    printTestBinary("chickens", "00111000010111001011000111000010100001101000100010001100");
    printTestBinary("eat",      "001101000111100001011");
    printTestBinary("happy",    "00101110011110000111100011110000110");
    printTestBinary("pickles!", "0001111001011000111000010100001001100110100001100011110");
}

}

</details>

And with that, I think your examples involving a '!' may be wrong. According to http://www.asciitable.com, '!' is 21 in hex, so 010 0001 in binary and 101 1110 negated.

Leading zero gets omitted before flipping the bits. That kept me busy for some time and prompted me to include the .replaceAll() part.

Scala cuz Java’s too verbose for me
Minified Format: (74 chars, 53 without function description)

def binary(s:String)=(""/:s)((r,c)=>r+(~c).toBinaryString.split("^1+")(1))

Normal Format: (85 chars, 61 without function description)
[spoiler]

def binary(s: String) = ("" /: s) ((r, c) => r + (~c).toBinaryString.split("^1+")(1))

[/spoiler]

Congratulations to @Saladoc for winning the fourth weekly programming contest! The next one will be opening up shortly!

If our code fulfilling the provided examples is optional, why do you include examples at all?

My apologies, I was very rushed when reviewing this. I’ve corrected my mistake.