Created
December 24, 2017 01:49
[2017-12-11] Challenge #344 [Easy] Baum-Sweet Sequence https://www.reddit.com/r/dailyprogrammer/comments/7j33iv/20171211_challenge_344_easy_baumsweet_sequence/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# [2017-12-11] Challenge #344 [Easy] Baum-Sweet Sequence | |
# https://www.reddit.com/r/dailyprogrammer/comments/7j33iv/20171211_challenge_344_easy_baumsweet_sequence/ | |
# | |
# In mathematics, the Baum–Sweet sequence is an infinite automatic sequence of 0s and 1s defined by the rule: | |
# | |
# b_n = 1 if the binary representation of n contains no block of consecutive 0s of odd length; | |
# b_n = 0 otherwise; for n >= 0. | |
# | |
# For example, b_4 = 1 because the binary representation of 4 is 100, which only contains one block of consecutive 0s of length 2; | |
# whereas b_5 = 0 because the binary representation of 5 is 101, which contains a block of consecutive 0s of length 1. | |
# When n is 19611206, b_n is 0. | |
# | |
# by Kory Becker | |
# http://primaryobjects.com | |
# | |
intToBin <- function(x) { | |
# Convert a number to a list of bits. | |
if (x == 1) | |
1 | |
else if (x == 0) | |
NULL | |
else { | |
mod <- x %% 2 | |
c(intToBin((x-mod) %/% 2), mod) | |
} | |
} | |
baumSweet <- function(number) { | |
z <- F | |
count <- 0 | |
odds <- 0 | |
for (bit in intToBin(number)) { | |
if (bit == 0) { | |
# Count consecutive zeroes. | |
z <- T | |
count <- count + 1 | |
} | |
else if (bit == 1) { | |
# Record the count of odd consecutive zeroes. | |
if (count %% 2 != 0) { | |
odds <- odds + 1 | |
} | |
count <- 0 | |
z <- F | |
} | |
} | |
if (z == T) { | |
if (count %% 2 != 0) { | |
odds <- odds + 1 | |
} | |
} | |
as.numeric(odds == 0) | |
} | |
baumSweetRange <- function(number) { | |
# Baum-Sweet from 0 to number. | |
sapply(0:number, function(n) { | |
c(baumSweet(n)) | |
}) | |
} | |
# Run the program. | |
print(baumSweet(4)) | |
print(baumSweet(5)) | |
print(baumSweet(19611206)) | |
result <- paste(baumSweetRange(20), collapse=', ') | |
answer <- '1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0' | |
print(result) | |
print(paste('Checking answer: ', result == answer)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1 | |
0 | |
0 | |
"1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0" | |
"Checking answer: TRUE" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment