#!/usr/bin/ruby -w # # Ruby Quiz #63, Grid Folding, take 2 # Creates XOR masks for the folds, generates the sequence directly. def fold2 h, v, folds hbits, vbits = folds.count("LR"), folds.count("TB") raise "Illegal folds #{folds}" unless hbits+vbits == folds.length raise "Folds imply #{1<= masks.length answer << (n ^= masks[i]) + 1 end end # Takes a sequence generated by folding, reproduces the fold # instructions (as best as possible) by recreating the masks. def unfold seq nfolds = seq.size.log2 mask = (seq[0]-1) ^ (seq[1]-1) hbits = ((mask.odd??mask : mask^((1< 1: answer += 1; n /= 2 end answer end def odd?; return self[0] == 1 end end require "fold" # Main program if $0 == __FILE__ h, v, folds = get_args a2 = fold2 h, v, folds a = fold h, v, folds raise "New folder returned\n #{a2.inspect}\nwhile old one returned\n #{a.inspect}" unless a == a2 unfolds = unfold a raise "Unfolding returned #{unfolds}" unless unfolds == folds or unfolds.tr("TBLR","LRTB") == folds p a p unfolds end