Collatz Sequence - The Sound of Numbers

A simple mathematical sequence that creates a surprisingly complex melody.

The iterator below yields a pair of values, the starting number of the sequence, and the number in each sequence.

Each integer is only visited once, to avoid too much repetition.

use_synth :piano

def each_collatz(n=1)
  transform = ->(n){n.even? ? n/2 : 3*n+1 }
  seq = n
  memo = {}
  loop do
    memo[seq] = true
    yield [n,seq]
    seq = transform.(seq)
    if memo[seq]
      n += 1
      seq = n

each_collatz(300) do |n,seq|
  puts "start number:#{n}, sequence:#{seq}"
  play 4*Math.log(seq,2)+32
  sleep 0.12

You can always tell the people who actually code in Ruby. :smiley:

I can’t wrap my head around lambdas and all that without a refresher, but that’s some beautiful serialism-esque output that that generates. :slight_smile:

Yes I’ve had a play too, and spent some time working out what the ruby was doing!
Now playing with using seveal sequences togther, also using another sequence to control parameters like cutoff (changed the synth to tb303 and slowed things down a bit)
This could be the source of lots of fun and experimentation.