Skip to content

Instantly share code, notes, and snippets.

@joriki
Last active June 5, 2020 05:44
Show Gist options
  • Save joriki/8f59c7e7f2d43dcc1bc0dc8080c2a154 to your computer and use it in GitHub Desktop.
Save joriki/8f59c7e7f2d43dcc1bc0dc8080c2a154 to your computer and use it in GitHub Desktop.
Count the binary strings that can be generated by alternatingly adding zeros and ones to either end; see https://math.stackexchange.com/questions/3706460.
import java.util.HashSet;
import java.util.Set;
public class Question3706460 {
public static void main(String [] args) {
Set<Long> strings = new HashSet<>();
strings.add(1L);
long bit = 2;
boolean one = false;
for (int n = 1;;n++,bit <<= 1,one = !one) {
System.out.println(n + " : " + strings.size() + " / " + Math.pow(strings.size(), 1. / n));
Set<Long> newStrings = new HashSet<>();
if (one)
for (Long s : strings) {
newStrings.add(s | bit);
newStrings.add((s << 1) | 1);
}
else
for (Long s : strings) {
newStrings.add(s);
newStrings.add(s << 1);
}
strings = newStrings;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment