input = File.read("input-16.txt").strip.split(",") #input = "s1,x3/4,pe/b".split(",") matcher = /([s,p,x])(?:(\w*\/\w*)|(\w+))/ line = ('a'..'p').to_a lines = [] #line = ('a'..'e').to_a # Found cycles after 60 runs actual_tries = 1000000000 % 60 (1..actual_tries).each do |i| lines << line.dup input.each do |s| match_data = (s.match matcher).to_a match_data[1] = match_data[1].to_sym case match_data[1] when :s line.rotate! -(match_data[3].to_i) when :x positions = match_data[2].split "/" line[positions[0].to_i], line[positions[1].to_i] = line[positions[1].to_i], line[positions[0].to_i] when :p buds = match_data[2].split "/" index_0, index_1 = line.find_index(buds[0]), line.find_index(buds[1]) line[index_0], line[index_1] = line[index_1], line[index_0] end end # if lines.include? line then # p "Cycle found after: #{i.to_s}" # break # end end p line.join