2水準系直行表の作成

2水準系直行表を作成するスクリプト

require 'terminal-table'
require 'csv'

def dup_row(rows)
  new_rows = []
  rows.each do |row|
    2.times do
      new_rows << row.dup
    end
  end
  new_rows
end

def add_cols(rows)
  c = [0,1].cycle
  new_rows = rows.dup
  new_rows.each do |row|
    d = c.next
    add_row = []
    row.each do |v|
      add_row << (v ^ d)
    end
    row << d
    row.concat(add_row)
  end
  new_rows
end

count = ARGV[0].to_i

rows = [[0], [1]]

Math.log2(count).to_i.times do
  rows = add_cols(dup_row(rows))
end

format = ARGV[1]

if format == "terminal"
  table = Terminal::Table.new do |t|
    t.headings = ["No."].concat rows.first.size.times.map { |i| i+1 }
    t.rows = rows.map.with_index do |row, i|
      ["##{i+1}"].concat(row)
    end
  end
  puts table
else
  csv_rows = []
  header = ["No."].concat rows.first.size.times.map { |i| i+1 }
  rows.each.with_index do |row, i|
    csv_rows << CSV::Row.new(header, ["##{i+1}"].concat(row))
  end
  table = CSV::Table.new(csv_rows)
  puts table
end

コマンド

第一引数は因子数

第二引数は表示形式。 terminal を指定すると表形式で表示。それ以外は CSVで出力

> ruby main.rb 15 terminal

結果

+-----+---+---+---+---+---+---+---+---+---+----+----+----+----+----+----+
| No. | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
+-----+---+---+---+---+---+---+---+---+---+----+----+----+----+----+----+
| #1  | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0  | 0  | 0  | 0  | 0  | 0  |
| #2  | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1  | 1  | 1  | 1  | 1  | 1  |
| #3  | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 | 0 | 0  | 0  | 1  | 1  | 1  | 1  |
| #4  | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1  | 1  | 0  | 0  | 0  | 0  |
| #5  | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 0 | 0 | 1  | 1  | 0  | 0  | 1  | 1  |
| #6  | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 0  | 0  | 1  | 1  | 0  | 0  |
| #7  | 0 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 1  | 1  | 1  | 1  | 0  | 0  |
| #8  | 0 | 1 | 1 | 1 | 1 | 0 | 0 | 1 | 1 | 0  | 0  | 0  | 0  | 1  | 1  |
| #9  | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0  | 1  | 0  | 1  | 0  | 1  |
| #10 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | 1  | 0  | 1  | 0  | 1  | 0  |
| #11 | 1 | 0 | 1 | 1 | 0 | 1 | 0 | 0 | 1 | 0  | 1  | 1  | 0  | 1  | 0  |
| #12 | 1 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 | 1  | 0  | 0  | 1  | 0  | 1  |
| #13 | 1 | 1 | 0 | 0 | 1 | 1 | 0 | 0 | 1 | 1  | 0  | 0  | 1  | 1  | 0  |
| #14 | 1 | 1 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 0  | 1  | 1  | 0  | 0  | 1  |
| #15 | 1 | 1 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 1  | 0  | 1  | 0  | 0  | 1  |
| #16 | 1 | 1 | 0 | 1 | 0 | 0 | 1 | 1 | 0 | 0  | 1  | 0  | 1  | 1  | 0  |
+-----+---+---+---+---+---+---+---+---+---+----+----+----+----+----+----+