试图在红宝石中创建矩阵 [英] trying to create a matrix in ruby

查看:89
本文介绍了试图在红宝石中创建矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为terain.dat的文件,其中包含以下矩阵:

i have a file called terain.dat which 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

我想读入文件并将第一行的第一个数字用作矩阵的大小(在这种情况下为10 X 10).然后用下面的数字填充10 X 10矩阵.

i want to read in the file and use the first number on the first line as the size of the matrix (which is 10 X 10 in this case). And then fill 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

我想知道这是否会构成10X10矩阵,以及如何填充它??

i was wondering if this will make a 10X10 matrix and how do i fill it??

推荐答案

实际上不是. Matrix.[]用于设置行的值. 因此,Matrix.[10,10]将创建一个包含2行的矩阵,并且在每列中创建10行.

actually no. The Matrix.[] is used for setting the values of a row. So Matrix.[10,10] would create a Matrix with 2 rows, and in each column a 10.

您要搜索的是Matrix.build(row_size, column_size),其中column_size默认为row_size.这为您提供了一个枚举器,可用于设置值. (或者您只需将一个块传递给Matrix.build

What you are searching for is Matrix.build(row_size, column_size) where column_size defaults to row_size. This gives you an enumerator which you can use to set the values. (or you just pass a block to Matrix.build

我建议使用另一种方法:

I'd 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 

这篇关于试图在红宝石中创建矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆