# Infinite SD-Score Hill using Koenigstuhl-format score files. # # Iteratively removes warriors based on the lowest value of the warrior's average # score multiplied by its standard deviation distance to the nearest warrior. hill = 'hill32' dat = File.read("#{hill}.dat").encode('UTF-8', invalid: :replace).split(/\r?\n/) warrs = dat.shift.to_i dat = dat.each_slice(4).to_a scores = File.read("#{hill}.scores").unpack('l*').each_slice(warrs).to_a.transpose scores.each_with_index { |row, i| row[i] = 0 } while dat.length > 1 wardisc = [] warrs -= 1 stddev = scores.transpose.map do |col| mean = col.sum.to_f / col.size Math.sqrt(col.sum { |x| (x - mean)**2 } / col.size) end scores.each_with_index do |x, i| mindist = Float::INFINITY scores.each_with_index do |y, j| mindist = [mindist, x.each_index.sum { |k| (x[k] - y[k]).abs / stddev[k] }].min if i != j end wardisc << [mindist * x.sum / 1e4 / warrs, mindist, x.sum / 1e4 / warrs] end lowest = wardisc.each_with_index.min_by { |val, idx| [val, -idx] }.last puts "#{warrs + 1} #{wardisc[lowest].map { |v| format('%7.3f', v) }.join(' ')} \"#{dat[lowest][0]}\" by #{dat[lowest][1]}" dat.delete_at(lowest) scores.delete_at(lowest) scores.each { |row| row.delete_at(lowest) } end puts "1#{' ' * 29}\"#{dat[0][0]}\" by #{dat[0][1]}"