spot7.org logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories

Filling/Populating a multidimensional array,, with elements of another array, and adding/incrementing values?


I read the documentation on Array more carefully.

An array can also be created by explicitly calling ::new with zero, one (the initial size of the Array) or two arguments (the initial size and a default object).

ary = Array.new    #=> []
Array.new(3)       #=> [nil, nil, nil]
Array.new(3, true) #=> [true, true, true]

Note that the second argument populates the array with references to the same object. Therefore, it is only recommended in cases when you need to instantiate arrays with natively immutable objects such as Symbols, numbers, true or false.

To create an array with separate objects a block can be passed instead. This method is safe to use with mutable objects such as hashes, strings or other arrays:

Array.new(4) { Hash.new } #=> [{},
{}, {}, {}]

This is also a quick way to build up multi-dimensional arrays:

 empty_table = Array.new(3) {
Array.new(3) }
 #=> [[nil, nil, nil], [nil, nil, nil], [nil,
nil, nil]]

Which means that I was modifying the element which was referenced in multiple places. And I had to explicitly create a new Array object for each entry along the new dimensions I was adding, so in a way building the extra dimension incrementally. There seem to be multiple ways of doing this. One is this method of a block sent to Array, and another is to do an iterator on the dimension and make a new Array for each entry.

I also found this post which highlights the problem in very simple terms:>>

The wrong way, and the way I see people trying often is to say Array.new( 4, Array.new(4, 0) ). In other words, an array of 4 rows, each row being an array of 4 zeroes. And this appears to work at first. However, run the following code:

 a = Array.new( 4, Array.new(4, 0) )
a[0][0] = 1 pp a 

It looks simple. Make a 4x4 array of zeroes, set the top-left element to 1. But print it and we get…

[[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0,
0], [1, 0, 0, 0]] 

It set the entire first column to 1, what gives? When we made the arrays, the inner-most call to Array.new gets called first, making a single row. A single reference to this row is then duplicated 4 times to fill the outer-most array. Each row is then referencing the same array. Change one, change them all.

Instead of passing a value to the Array.new method, we pass a block. The block is executed every time the Array.new method needs a new value. So if you were to say Array.new(5) { gets.chomp }, Ruby will stop and ask for input 5 times. So all we need to do is just create a new array inside this block. So we end up with Array.new(4) { Array.new(4,0) }. Now let's try that test case again.

 a = Array.new(4) { Array.new(4, 0) }
a[0][0] = 1 pp a 

And it does just as you'd expect.

 [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0,
0], [0, 0, 0, 0]]

Categories : Ruby

Related to : Filling/Populating a multidimensional array,, with elements of another array, and adding/incrementing values?
Filling out array values on "negative" positions
#include <stdio.h> #include <string.h> int main() { char original[16] = "ABCDEF"; char other[16] = {0}; size_t len = strlen(original); memset(other, '-', len + 4); memcpy(other + 3, original, len); puts(other); sprintf(other, "---%s-", original); puts(other); memmove(original + 3, original, len);//move to back + 3 memset(original, '-', 3);

Categories : C
Multidimensional array concatenate values of the same id(key)
Try this - $array = array(); foreach ($yourArray as $val) { if (!array_key_exists($val['id'], $array)) { $array[$val['id']] = $val; } else { $array[$val['id']]['content'] .= ' '.$val['content']; } }

Categories : PHP
Ruby - Compare array element values against other elements
This works OK, but it's not elegant or efficient: a.reject { |e1| a.any? { |e2| e1 != e2 && e2[:salary] <= e1[:salary] && e2[:products] >= e1[:products] } } The problem is that it's O(n^2) - for each element in the array it traverses the array again. If efficiency isn't a huge problem for you then this is probably clearest to start with. The only other solutions that spri

Categories : Ruby
How do you copy over an array of no elements to an output file so that it contains an empty array?
fopen( bobby.txt , "wb" ); This is wrong. fopen( "bobby.txt" , "wb" ); The array has nothing in it and your are trying to copy nothing to a file? This sounds contradictory. When there is nothing in the array don't write it to a file. If you want to check whether the file exists or not check the below link. What's the best way to check if a file exists in C? (cross platform)

Categories : C
Populating array in Javascript using setInterval function
Because you are using setInterval, with a 1 second delay, to add to the array the last line console.log(array); is executed before any of the interval function so the array would still be empty then. Good info here: http://javascript.info/tutorial/settimeout-setinterval

Categories : Javascript
Recently Add
'on raise' hook in ruby
Ruby OCI8 - bind optional parameters to Oracle Stored procedure
How to install the app only once for the suite
Different test unit output in Rubymine and console
Can Rake run each test in a separate Ruby instance?
Ruby strftime in UK format i.e. dd/mm/yy
Accessing hash in Ruby like objects in Coffeescript
How do I correct my script, that it doesn't matter what file name has the .xml that is uploaded?
Ruby: Tests not runing
Do I have to install Ruby on my Apache server to run scripts
Ruby: Does Test::Unit still exist?
How do I make a form that changes color with input text in Ruby?
compose objects without initializing objects that are not in hash
Undefined local variable or method in Rspec test?
How to enable Rubocop with Syntastic Vim plugin and Rbenv?
package.json (javascript npm) or requirements.txt (python pip) equivalent for ruby
Word Count (Ruby)
How do I get my parser atom to terminate inside a rule including optional spaces?
CSV objects in Ruby. What are they exactly?
Rails+ActiveAdmin - filtering with ransacker throws an error PG::SyntaxError: ERROR: syntax error at or near ","
Web starter kit installation Error
How can I override Hash native brackets ([] access)
Amazon S3 secure URL at the bucket level
Tagging exceptions in Ruby, an explanation/alternative
Two thirds histogram Ruby
Combining words in a string into anagrams using ruby
Ruby SHA2 digest incorrect doc or issue in my IRB?
Regular expressions in Ruby with special characters
How to create a case insensitive Regexp from a non-case insensitive Regexp?
Converting string to date with Ruby
© Copyright 2017 spot7.org Publishing Limited. All rights reserved.