Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@karashi39
Created February 23, 2018 04:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karashi39/7f1016814f26b895de144b95446fdf90 to your computer and use it in GitHub Desktop.
Save karashi39/7f1016814f26b895de144b95446fdf90 to your computer and use it in GitHub Desktop.
hoge
# frozen_string_literal: true
# 各行、各列の合計値の正解を計算する関数
def calc_general_sum(magic_table)
general_sum = 0
magic_table.each do |line|
line.include?(0) && next
general_sum = line.inject(:+)
break
end
# もし合計値がわからない場合は、行列入れ替えて再帰
general_sum.zero? && general_sum = calc_general_sum(magic_table.transpose)
return general_sum
end
# 受け取った魔法陣を出力する関数
def print_magic_table(magic_table)
magic_table.each do |line|
puts line.join(' ')
end
end
# 0を含む行のの配列を受け取って、正しい配列に変更
def get_complete_line(line, complete_num)
line_str = line.join(' ').sub!(/0/, complete_num.to_s)
line = line_str.split(' ').map(&:to_i)
return line
end
# 0を含む魔法陣を受け取って、0の値を正しいものに直して返す関数
def complete_magic_table(magic_table, general_sum)
magic_table.each_with_index do |line, i|
line.count(0).zero? && next
if line.count(0) == 1
complete_num = general_sum - line.inject(:+)
magic_table[i] = get_complete_line(line, complete_num)
elsif line.count(0) == 2
# 0が横に並んでいる時は、大変だから行列を入れ替えて再帰
magic_table = complete_magic_table(magic_table.transpose, general_sum)
magic_table = magic_table.transpose
end
end
return magic_table
end
# 入力受取部分
table_size = gets.to_i
input_magic_table = []
table_size.times do
input_line = gets.split(' ').map(&:to_i)
input_magic_table.push(input_line)
end
general_sum = calc_general_sum(input_magic_table)
true_magic_table = complete_magic_table(input_magic_table, general_sum)
print_magic_table(true_magic_table)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment