当我有一张桌子;阅读表的一半部分
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
感谢
当我有一张桌子;阅读表的一半部分
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
感谢
这里假设你有你的表在文件中的某个地方,但你可以基本上只是从不管你想要开始串门:
# 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 } }
虽然我认为如果方法是非破坏性的会更好。 – Jeriko 2010-06-08 10:50:22
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) }
我打算假设你的表总是正方形的,而你创建init的方式ial table并不是那么重要。
# 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}
。
将非空间/时间有效的解决方案吗? – 2010-06-08 09:42:53