Learning Ruby with AtCoder 13 How to make a two-dimensional array

Introduction

Participating in competitive programming as part of learning Ruby and algorithms. Here, we output what we learned during learning.

This time about how to make a two-dimensional array. In the 3rd algorithm test 2nd question Dynamic scoring There is a scene where I want to use a two-dimensional array. I've had a little trouble here, so I'll summarize it for review.

Thing you want to do

I wanted to do something like the following, so I decided to make a two-dimensional array.

For example Three participants (1,2,3) participate in an exam. The exam will have three questions. Manage whether each participant was able to answer each question.

The image looks like the one below.

image


#① Make a two-dimensional array like this
[[0, 0, 0],[0, 0, 0],[0, 0, 0]]

#② If Participant 1 answers the first question correctly, put 1 in the corresponding element.
[[1, 0, 0],[0, 0, 0],[0, 0, 0]] #1 in the first element of the array of first elements

#③ Next, if Participant 3 answers the second question correctly, put 1 in the corresponding element.
[[1, 0, 0],[0, 0, 0],[0, 1, 0]] #1 in the second element of the third element array

① What you did first (wrong)

ary = Array.new(3, Array.new(3, 0))
print ary
# => [[0, 0, 0],[0, 0, 0],[0, 0, 0]]

As for the appearance, I have made what I want to make, When I try to record the answer

ary[0][0] = 1
print ary
# => [[1, 0, 0],[1, 0, 0],[1, 0, 0]]

I intended to make changes only to the array of the first element, but it affected all the arrays.

② Use the map method (correct answer!)

ary = Array.new(3).map{Array.new(3,0)}
print ary
# => [[0, 0, 0],[0, 0, 0],[0, 0, 0]]

ary[0][0] = 1
print ary
# => [[1, 0, 0],[0, 0, 0],[0, 0, 0]]

As a result, by entwining the map method, I was able to safely create the array as I imagined.

What's the difference

The two-dimensional arrays (1) and (2) above look exactly the same, but they seem to have completely different properties. I will think about what is different.

About new method ① of Array class

In Reference, it is written as follows.

new(size = 0, val = nil) -> Array

Generates an array of length size, initializes each element with val and returns it. Note that val is not duplicated element by element. All elements refer to the same object val.

Example


ary = Array.new(3, "foo")
p ary                     #=> ["foo", "foo", "foo"]
ary[0].capitalize!
p ary                     #=> ["Foo", "Foo", "Foo"]

In this example, the "foo" in each element is shown to be the same object. As the description says, all elements are the same object val.

Then, is the two-dimensional array created in ① the following image?

1.jpg

Even if the elements appear to be divided into three parts in the array, they only refer to the same object in the end. It seems that no matter which element you change, the same object will change.

Array.new(3, Array.new(3, 0)).jpg

Is it such an image?

About map method ②

In Reference, it is written as follows.

map -> Enumerator map {|item| ... } -> [object]

Returns an array containing all the results of evaluating the block for each element. If you omit the block, perform the iteration described above and Returns an Enumerator object that returns the resulting array.

Example


#All triple
p [1, 2, 3].map {|n| n * 3 }  # => [3, 6, 9]

The map method, like the each method, extracts elements one by one from the array object and Returns the result of processing in the block {} as an array.

So, does the two-dimensional array created in ② have the following image?

2.jpg

Since an array is generated separately for each element, they exist as independent objects. So it seems that you can make changes separately.

Finally

So far, I have summarized the points that I stumbled upon in how to create a two-dimensional array. I intend to summarize it while reading the reference etc. If you have any mistakes, I would be grateful if you could point them out.

Recommended Posts

Learning Ruby with AtCoder 13 How to make a two-dimensional array
How to make a Java array
Learning Ruby with AtCoder 11 How to receive frequently used standard input
[Java] How to turn a two-dimensional array with an extended for statement
[Ruby] Extracting a two-dimensional array
How to make a factory with a model with polymorphic association
Learning Ruby with AtCoder 12 How to use standard output properly (p / puts / print)
Learning Ruby with AtCoder 6 [Contest 168 Therefore]
How to change a string in an array to a number in Ruby
How to make a JDBC driver
How to make a splash screen
How to make a Jenkins plugin
How to make a Maven project
Make a typing game with ruby
Try to imitate the idea of a two-dimensional array with a one-dimensional array
How to make a jar file with no dependencies in Maven
How to make a Java calendar Summary
Learning Ruby with AtCoder 7 [Contest 168 Triple Dots]
How to add a new hash / array
How to make a Discord bot (Java)
Let's make a smart home with Ruby!
Ruby two-dimensional array
How to build a Ruby on Rails development environment with Docker (Rails 6.x)
If you want to make a zip file with Ruby, it's rubyzip.
How to build a Ruby on Rails development environment with Docker (Rails 5.x)
How to make an app with a plugin mechanism [C # and Java]
AtCoder Beginner Contest 169 A, B, C with ruby
Convert a string to a character-by-character array with swift
How to create pagination for a "kaminari" array
How to make a lightweight JRE for distribution
AtCoder ABC127 D hash to solve with Ruby 2.7.1
[Ruby] How to generate a random alphabet string
How to make a follow function in Rails
I tried to make a machine learning application with Dash (+ Docker) part3 ~ Practice ~
How to make a judgment method to search for an arbitrary character in an array
Rails6 I want to make an array of values with a check box
Learning Ruby with AtCoder 9 [1st Algorithm Practical Test 3rd] Sorting of array elements
How to make shaded-jar
[Ruby] I want to make an array from a character string with the split method. And vice versa.
How to make batch processing with Rails + Heroku configuration
How to use an array for a TreeMap key
Solving with Ruby and Java AtCoder ABC129 D 2D array
How to delete a new_record object built with Rails
How to make an almost static page with rails
How to organize information to make programming learning more efficient
Let's make a LINE Bot with Ruby + Sinatra --Part 2
How to make JavaScript work on a specific page
How to manually generate a JWT with Rails Knock
AtCoder Beginner Contest 170 A, B, C up to ruby
How to launch another command in a Ruby program
How to output standard from an array with forEach
[How to insert a video in haml with Rails]
How to make Laravel faster with Docker for Mac
How to convert a file to a byte array in Java
How to query Array in jsonb with Rails + postgres
Let's make a LINE Bot with Ruby + Sinatra --Part 1
How to make a cache without thinking too much
How to make a mod for Slay the Spire
How to get started with creating a Rails app
[Java] How to start a new line with StringBuilder
How to find the total value, average value, etc. of a two-dimensional array (multidimensional array)-java