k.go 919 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package kata
  2. import (
  3. "fmt"
  4. )
  5. type state byte
  6. /*
  7. The sequence is documented as only being tested for up to 1E6, i.e. 24 bits.
  8. It is assumed to ignore leading zeroes.
  9. A faster solution might use the 2-automaton mechanism described in
  10. https://www.emis.de//journals/SLC/opapers/s30allouche.pdf
  11. */
  12. func BaumSweet(ch chan<- int) {
  13. // Handle n == 0 as binary empty string, par kata discussion.
  14. ch <- 1
  15. N_LOOP:
  16. for n := 1; n < 1E4+1; n++ {
  17. // Adding external 1s does not changes the result, and ensures the potential
  18. // final 0 sequence is measured without a special case.
  19. s := []byte(fmt.Sprintf("1%b1", n))
  20. // Runes will be '0' and '1' by construction, so always single-byte.
  21. segmentLength := 0
  22. for i := 0; i < len(s); i++ {
  23. if s[i] == '1' {
  24. if segmentLength%2 == 1 {
  25. ch <- 0
  26. continue N_LOOP
  27. } else {
  28. // Do nothing
  29. }
  30. } else {
  31. segmentLength++
  32. }
  33. }
  34. ch <- 1
  35. }
  36. }