Trying to create a ruby ​​matrix

I have a terain.dat file that contains this matrix:

10 1 1 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 12 12 12 1 2 3 4 5 6 7 12 12 12 1 2 3 4 5 6 7 12 12 12 

I want to read in the file and use the first number in the first line as the size of the matrix (in this case it is 10 X 10). And then fill in the 10 X 10 matrix with the numbers below.

this is what i have so far:

  class Terrain def initialize file_name @input = IO.readlines(file_name) #read in file # reads in the file with the terrain detials @matrix_size = @input[0].to_i # changes the first index to an int (so i can make a10X10 matrix) @land = Matrix.[@matrix_size, @matrix_size] # will this make a 10 X 10 matrix?? end end 

I was wondering if the 10X10 matrix would do this and how to fill it?

+1
source share
5 answers

not really. Matrix.[] used to set row values. Thus, Matrix.[10,10] will create a matrix with two rows, and in each column - 10.

What you are looking for is Matrix.build(row_size, column_size) , where column_size by default. This gives you an enumerator that you can use to set values. (or you just pass the Matrix.build block

I suggest a different approach:

 arr = [] @input.each_index do |index| arr[index] = @input[index].split ' ' end @land = Matrix.build(10,10) do |row, column| arr[row][column].to_i end 
+3
source

I would write:

 terrain = open("terrain.data") do |file| size = file.lines.first.to_i rows = file.lines.first(size).map { |line| line.split.map(&:to_i) } Matrix.rows(rows) end 
+3
source

You can skip the first line, read the other lines, delete them to remove new lines, and then split by space. This will give you an array of arrays that you can pass to Matrix.rows .

0
source

No need to declare size. Try the following:

 class Terrain attr_accessor :m def initialize file_name data = IO.readlines(file_name) data.each_line do |l| data << l.split.map {|e| e.to_i} end @m = Matrix[*@data] end end 

Or even better:

 class Terrain attr_accessor :m def initialize file_name File.open(file_name).each do |l| data << l.split.map {|e| e.to_i} end @m = Matrix[*@data] end end 
0
source

No size required:

 class Terrain def initialize(file_name) File.open(file_name) do |f| @m = Matrix[*f.lines.map { |l| l.split.map(&:to_i) }] end end end 
0
source

Source: https://habr.com/ru/post/1379995/


All Articles