SATURN  RING  STATION

At a distant space view post, we chat about codes.

r/dailyprogrammer : generating Baum–Sweet sequence

I really like r/dailyprogrammer, started a series posting my solutions/thoughts.

 

 

[2017-12-11] Challenge #344 [Easy] Baum-Sweet Sequence

Wikipedia: Baum-Sweet sequence

 

 

get1 method is my first draft in Java, get2 is a better version by another redditor with similar approach.

    public static void main(String[] args) {
        IntStream.range(0,20).forEach(i -> System.out.print(BaumSweet.get1(i) + ", "));
    }

    public static class BaumSweet {

        private static int get1(int num) {
            String binary = Integer.toBinaryString(num);
            if (num == 0) return 1; // special case

            for (int i = 0; i<binary.length(); i++){
                if (binary.charAt(i) == '0') {
                    int j = i;
                    int c = 1;
                    // When we meet 0, start tracking
                    while (binary.length() > (j + 1) && binary.charAt(j + 1) == '0') {
                        j++;
                        c++;
                    }
                    if (c % 2 == 1) {
                        return 0;
                    }
                    i = j;  // skipping 0(s) for for-loop
                }
            }
            return 1;
        }

        private static int get2(int num) {
            String binary = Integer.toBinaryString(num);
            if (num == 0) return 1;

            int c = 0;
            for (int i = 0; i < binary.length(); i++) {
                if (binary.charAt(i) == '0') {
                    c++;
                } else {
                    if (c % 2 != 0) {
                        return 0;
                    }
                    c = 0;
                }
            }
            if (c % 2 != 0) {
                return 0;
            }
            return 1;
        }
    }

 

 

Then I looked at the others’ stream approach utilizing the String split() method. Really learnt something here. For simplicity, it doesn’t handle the n = 0 special case.

IntStream.range(0,20)
        .mapToObj(i ->
            Arrays.stream(Integer.toBinaryString(i).split("1"))
                .anyMatch(str-> str.length() % 2 == 1))
        .collect(Collectors.toList()).forEach(b -> System.out.print((b?0:1) + ", "));

 

Here is a JavaScript version with split() and arrow function.

function baumTest(num) {
    let bin = num.toString(2);
    if (bin == "0") {
        return 1;
    }

    if (bin.split("1").some(x => x.length%2 == 1)) {
        return 0;
    } else {
        return 1;
    }
}

let baumArray = new Array(21).fill().map((e, i) => i++).map(x => baumTest(x));
console.log(baumArray);

 

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

r/dailyprogrammer : generating Baum–Sweet sequence