读表的一半

时间:2010-06-08 09:08:45

标签: ruby

当我有桌子时;

1 0 0 1 0
0 1 0 1 0
0 0 1 0 1
1 1 1 1 0
0 0 0 0 1

假设我只想读取并保持此表的上对角线上的值,我怎样才能在纯红宝石中轻松完成此操作?

这样最终的结构看起来像

1 0 0 1 0
  1 0 1 1 
    1 0 1
      1 0
        1

由于

3 个答案:

答案 0 :(得分:2)

这假设您将表格放在某个文件中,但基本上只需从您想要开始的地方开始:

# get data from file
data = File.readlines(path).map(&:chomp)

# convert to array of integers
a = data.map { |line| line.split(" ").map(&:to_i) }

# remove incrementally more elements from each row
a.each_index { |index| a[index].slice!(0,index) }

# alternatively, you could set these to nil
# in order to preserve your row/column structure
a.each_index { |index| index.times { |i| a[index][i] = nil } }

答案 1 :(得分:1)

input = File.new(filename, "rb")
firstRow = input.readline().split(" ").map  { |el| el.to_i }
len = firstRow.length
table = [firstRow]
remaining = input.readlines().map { |row| row.split(" ").map { |el| el.to_i } }
(len - 1).times  { |i| table << remaining[i].slice(i + 1, len - i - 1) }

答案 2 :(得分:1)

我假设你的表总是方形的,你创建初始表的方式并不是那么重要。

# Create a two-dimensional array, somehow.
table = []
table << %w{1 0 0 1 0} 
table << %w{0 1 0 1 0}
table << %w{0 0 1 0 1}
table << %w{1 1 1 1 0}
table << %w{0 0 0 0 1}

# New table
diagonal = []
table.each_with_index {|x,i| diagonal << x[0,table.size - i]}

# Or go the other direction
diagonal = []
table.each_with_index {|x,i| diagonal << x[0,i+1]}

如果你需要将值作为整数,那么在那里扔一个map {|i| i.to_i}