Reputation: 2226
When i have a table;
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
Say i want to only read and keep the values along the upper diagonal of this table, how can i easily accomplish this in pure ruby?
Such that the final structure looks like
1 0 0 1 0
1 0 1 1
1 0 1
1 0
1
Thanks
Upvotes: 1
Views: 106
Reputation: 329
I'm going to assume your table is always square, and the way you create the initial table isn't all that important.
# 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]}
If you need the values to be integers, then throw a map {|i| i.to_i}
in there somewhere.
Upvotes: 1
Reputation: 6637
This assumes you have your table in a file somewhere, but you can basically just drop in from wherever you want to start:
# 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 } }
Upvotes: 2
Reputation: 284927
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) }
Upvotes: 1