out_file = File.open "out_file.txt" , 'w' do |f|
matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
f.puts "matrix test"
f.puts " int at [0,2]: #{matrix[0][2]}"
f.puts " int at [2,0]: #{matrix[2][0]}"
f.puts " int at {1,1]: #{matrix[1][1]}"
above code produces this:
"matrix test
int at [0,2]: 3
int at [2,0]: 7
int at {1,1]: 5"
but this code using the same matrix variable declaration ..
rows = Array(0..3)
cols = Array(0..3)
rows.each do |r|
cols.each do |c|
f.puts "row:#{r} col:#{c} = #{matrix[r][c]},"
end
end
produces an error:
undefined method `[]' for nil:NilClass (NoMethodError)
Can anybody please tell me what's going on?
The problem is your Array(0..3), it is generating an array [0,1,2,3] instead of what you want: [0,1,2].
You actually want to use ... : Array(0...3) => [0,1,2].
Or you could just change the range inside to 0..2 : Array(0..2) => [0,1,2]
Check out the documentation for Range for more information.
As Tony suggests, using rows=Array(0..2) or rows=Array(0...3) will work for you.
You can also use the range directly and forgo the array creation, like this:
rows = 0...3
cols = 0...3
...
There are 2 types of ranges, the inclusive .. and the exclusive ... which doesn't include the right most digit.
A range such as 0..5 will have every number including the 5. (ie. 0,1,2,3,4,5)
A range such as '0...5' will have every number excluding the 5. (ie. 0,1,2,3,4).
So if you notice your error message,
undefined method `[]' for nil:NilClass (NoMethodError)
You need to begin to wonder what could be running a method on nil. Well, you have this matrix declaration of:
matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
So that when this range pops up that is expressed as:
rows = Array(0..3)
It will go through 0,1,2, and also 3. Well, there is no 3 index in that array since your array begins counting at 0 and ends at 2. So when the 3 index hits, the value of it is beyond anything you've declared - it's nil. When you try to run that method on it (to call the spot in the array you want), the error message tells you that you can't run a method (which the [] is actually) on nil.
Paying close attention to your error messages, as well as understanding the 2 types of ranges should help you catch these sorts of errors in the future as well. Leave a comment if this doesn't make total sense.
The previous answers are right, but I thought I would raise the issue of the approach...
Why are you creating ranged arrays instead of using the actual length of the matrix arrays in question...?
Maybe something like this would remove the need to assume the matrix's composition:
out_file = File.open "out_file.txt" , 'w' do |f|
matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
f.puts "matrix test"
matrix.length.times do |r|
matrix[r].length.times do |c|
f.puts "row:#{r} col:#{c} = #{matrix[r][c]},"
end
end
Related
I am trying to initialize an array of Nullable Integers with a given size. My intend is to add elements to the array and to be able to count the number of Nullable elements in an array.
However I noticed the following behavior. Running the following code:
function main()
arr = Array{Nullable{Int}}(10)
res = 0
for i in 1:10
if isnull(arr[i])
res += 1
end
end
res
end
is expected to return 10, however the program returns different values almost every time that I run the code. Initializing just the array:
function main()
arr = Array{Nullable{Int}}(10)
end
this is the result:
Nullable{Int64}(7142821636481377634)
Nullable{Int64}(8803814271447229814)
Nullable{Int64}(7935455170894001012)
Nullable{Int64}(8247625210579135584)
Nullable{Int64}(7815275285807655200)
Nullable{Int64}()
Nullable{Int64}()
Nullable{Int64}()
Nullable{Int64}()
Nullable{Int64}()
Here one can see that not all elements are in fact not Null. Which would explain why the function isnull() does not recognize them as Null objects.
This is the desired effect:
function main()
arr = Array{Nullable{Int}}(10)
for i in 1:10
arr[i] = Nullable{Int}()
end
println(arr)
end
which indeed returns an array of Nullable elements. However, it seems a bit tedious to run this code for initialization.
Any ideas how this can be avoided?
In Julia 0.6 you can use arr = fill(Nullable{Int64}(),10).
Note however that Nullables are depreciated in Julia 0.7 (https://github.com/JuliaLang/julia/blob/master/NEWS.md), consider to use the Nothing or Missing types instead:
julia> vector_with_nothing_or_int = Vector{Union{Int64, Nothing}}(nothing,10)
10-element Array{Union{Nothing, Int64},1}:
nothing
nothing
[...]
julia> vector_with_missing_or_int = Vector{Union{Int64, Missing}}(missing,10)
10-element Array{Union{Missing, Int64},1}:
missing
missing
[...]
Check if a element is nothing or missing can be done with:
julia> vector_with_nothing_or_int[1] == nothing
true
julia> ismissing(vector_with_missing_or_int[1])
true
The Missing type also works in Julia 0.6 if you load the module Missings. This is the corresponding code for Julia 0.6:
using Missings
vector_with_missing_or_int = Vector{Union{Int64, Missing}}(10)
vector_with_missing_or_int .= missing
vector_with_nothing_or_int = Vector{Union{Int64, Nothing}}(10)
vector_with_nothing_or_int .= nothing
The operator .= replaces every element of the array with the element of the right. All these examples also work for multi-dimensional arrays if you replace Vector by Array when you specify also the number of dimensions.
I'm working on a method that takes an array of words as a param and returns an array of arrays, where each subarray contains words that are anagrams of each other. The line while sort_array[i][1]==temp do is throwing undefined method '[]' for nil:NilClass (NoMethodError) and I have no idea why.
def combine_anagrams(words)
sort_array = Hash.new
words.each do |w|
sort_array[w] = w.split("").sort
end
sort_array = sort_array.sort_by { |w, s| s }
return_array = []
i = 0
while i<sort_array.length do
temp_array = []
temp = sort_array[i][1]
while sort_array[i][1]==temp do
temp_array += [sort_array[i][0]]
i+=1
end
return_array += [temp_array]
end
return temp_array
end
p combine_anagrams( ['cars', 'for', 'potatoes', 'racs', 'four','scar', 'creams','scream'] )
It looks like this is because you are incrementing your i variable without checking to make sure you're still in bounds of the sort_array. To see the problem, put an puts statement in your code inside the inner most while loop:
while sort_array[i][1]==temp do
temp_array += [sort_array[i][0]]
i+=1
puts "i is #{i} and the length is #{sort_array.length}"
end
and then run your code and you'll see:
i is 1 and the length is 8
i is 2 and the length is 8
i is 3 and the length is 8
i is 4 and the length is 8
i is 5 and the length is 8
i is 6 and the length is 8
i is 7 and the length is 8
i is 8 and the length is 8
example.rb:15:in `combine_anagrams': undefined method `[]' for nil:NilClass (NoMethodError)
You need to make sure on both while loops that you stay within the bounds of your array, for instance:
while i < sort_array.length && sort_array[i][1]==temp do
end
As a side note, your code is currently only going to return the last temp_array, since you're also resetting that at the beginning of your outer while loop. And, if I understand what problem you're trying to solve you might want to look at group_by available on Array thanks to the Enumerable module:
words = ['cars', 'for', 'potatoes', 'racs', 'four','scar', 'creams','scream']
words.group_by { |word| word.chars.sort }.values
# => [["cars", "racs", "scar"], ["for"], ["potatoes"], ["four"], ["creams", "scream"]]
I wrote method, to sort array of user inputs(integers) from low to high and reverse. Code looks like:
def alphabetize(arr, rev=false)
arr.sort!
if rev==true
arr.reverse!
end
return arr
end
puts "enter your numbers with 'space' between them"
text = gets.chomp
numbers = text.split(" ")
numbers.each do |element|
element.to_i
end
puts alphabetize(numbers)
First time i tried only numbers from 0 to 9, and method had worked correct. But then i tried to input numbers like 1112, 11, 22 and after sorting procedure, i had got result like this "11 1112 22". After this, i tried to change code this way:
def alphabetize(arr, rev=false)
arr.sort!{|a, b| a.to_i <=> b.to_i}
if rev==true
arr.reverse!
end
return arr
end
puts "enter your numbers with 'space' between them"
text = gets.chomp
numbers = text.split(" ")
puts alphabetize(numbers)
And this way my code works correct and sorting input of 11, 1112, 22 produce the result that i expect: "11, 22, 1112". Looks like i have solved the problem, but i really want to understand the difference between first version and second version of code. Why method sort works in different ways?
each does not replace the elements in an array - it simply returns the array itself (without change).
You might prefer to use map:
numbers = numbers.map do |element|
element.to_i
end
Or, better yet, use map!, which actually changes the array itself, rather than return the changed array:
numbers.map! do |element|
element.to_i
end
You can also use the following shorthand:
numbers.map! &:to_i
Looks like in the first place you still comparing strings instead of integers.
In fact, in the first place you don't convert elements to integers:
numbers.each do |element|
element.to_i
end
The script below don't replace strings with integers in array.
I have two arrays like this:
a = [{'one'=>1, 'two'=>2},{'uno'=>1, 'dos'=>2}]
b = ['english', 'spanish']
I need to add a key-value pair to each hash in a to get this:
a = [{'one'=>1, 'two'=>2, 'language'=>'english'},{'uno'=>1, 'dos'=>2, 'language'=>'spanish'}]
I attempted this:
(0..a.length).each {|c| a[c]['language']=b[c]}
and it does not work. With this:
a[1]['language']=b[1]
(0..a.length).each {|c| puts c}
an error is shown:
NoMethodError (undefined method '[]=' for nil:NilClass)
How can I fix this?
a.zip(b){|h, v| h["language"] = v}
a # => [
# {"one"=>1, "two"=>2, "language"=>"english"},
# {"uno"=>1, "dos"=>2, "language"=>"spanish"}
# ]
When the each iterator over your Range reaches the last element (i.e. a.length), you will attempt to access a nonexisting element of a.
In your example, a.length is 2, so on the last iteration of your each, you will attempt to access a[2], which doesn't exist. (a only contains 2 elements wich indices 0 and 1.) a[2] evaluates to nil, so you will now attempt to call nil['language']=b[2], which is syntactic sugar for nil.[]=('language', b[2]), and since nil doesn't have a []= method, you get a NoMethodError.
The immediate fix is to not iterate off the end of a, by using an exclusive Range:
(0...a.length).each {|c| a[c]['language'] = b[c] }
By the way, the code you posted:
(0..a.length).each {|c| puts c }
should clearly have shown you that you iterate till 2 instead of 1.
That's only the immediate fix, however. The real fix is to simply never iterate over a datastructure manually. That's what iterators are for.
Something like this, where Ruby will keep track of the index for you:
a.each_with_index do |hsh, i| hsh['language'] = b[i] end
Or, without fiddling with indices at all:
a.zip(b.zip(['language'].cycle).map(&:reverse).map(&Array.method(:[])).map(&:to_h)).map {|x, y| x.merge!(y) }
[Note: this last one doesn't mutate the original Arrays and Hashes unlike the other ones.]
The problem you're having is that your (0..a.length) is inclusive. a.length = 2 so you want to modify it to be 0...a.length which is exclusive.
On a side note, you could use Array#each_with_index like this so you don't have to worry about the length and so on.
a.each_with_index do |hash, index|
hash['language'] = b[index]
end
Here is another method you could use
b.each_with_index.with_object(a) do |(lang,i),obj|
obj[i]["language"] = lang
obj
end
#=>[
{"one"=>1, "two"=>2, "language"=>"english"},
{"uno"=>1, "dos"=>2, "language"=>"spanish"}
]
What this does is creates an Enumerator for b with [element,index] then it calls with_object using a as the object. It then iterates over the Enumerator passing in each language and its index along with the a object. It then uses the index from b to find the proper index in a and adds a language key to the hash that is equal to the language.
Please know this is a destructive method where the objects in a will mutate during the process. You could make it non destructive using with_object(a.map(&:dup)) this will dup the hashes in a and the originals will remain untouched.
All that being said I think YAML would be better suited for a task like this but I am not sure what your constraints are. As an example:
yml = <<YML
-
one: 1
two: 2
language: "english"
-
uno: 1
dos: 2
language: "spanish"
YML
require 'yaml'
YAML.load(yml)
#=>[
{"one"=>1, "two"=>2, "language"=>"english"},
{"uno"=>1, "dos"=>2, "language"=>"spanish"}
]
Although using YAML I would change the structure for numbers to be more like language => Array of numbers by index e.g. {"english" => ["zero","one","two"]}. That way you can can access them like ["english"][0] #=> "zero"
I am trying to find the duplicate values in an array of strings between 1 to 1000000.
However, with the code I have, I get the output as all the entries that are doubled.
So for instance, if I have [1,2,3,4,3,4], it gives me the output of 3 4 3 4 instead of 3 4.
Here is my code:
array = [gets]
if array.uniq.length == array.length
puts "array does not contain duplicates"
else
puts "array does contain duplicates"
print array.select{ |x| array.count(x) > 1}
end
Also, every time I test my code, I have to define the array as array = [1,2,3,4,5,3,5]. The puts works but it does not print when I use array [gets].
Can someone help me how to fix these two problems?
How I wish we had a built-in method Array#difference:
class Array
def difference(other)
h = other.tally
reject { |e| h[e] > 0 && h[e] -= 1 }
end
end
though #user123's answer is more straightforward. (Array#difference is probably the more efficient of the two, as it avoids the repeated invocations of count.) See my answer here for a description of the method and links to its use.
In a nutshell, it differs from Array#- as illustrated in the following example:
a = [1,2,3,4,3,2,4,2]
b = [2,3,4,4,4]
a - b #=> [1]
a.difference b #=> [1, 3, 2, 2]
For the present problem, if:
arr = [1,2,3,4,3,4]
the duplicate elements are given by:
arr.difference(arr.uniq).uniq
#=> [3, 4]
For your first problem, you need to uniq function like
array.select{ |x| array.count(x) > 1}.uniq
For your second problem, when you receive a value using array = [gets] it would receive your entire sequence of array numbers as a single string, so everything would be stored in a[0] like ["1, 2 3 4\n"].
puts "Enter array"
array = gets.chomp.split(",").map(&:to_i)
if array.uniq.length == array.length
puts "array does not contain duplicates"
else
puts "array does contain duplicates"
print array.select{ |x| array.count(x) > 1}.uniq
end
copy this code in ruby file and try to run using
ruby file_name.rb
Coming to your 'gets' problem,
When you are doing a gets, your are basically getting a string as an input but not an array.
2.2.0 :001 > array = [gets]
1,2,1,4,1,2,3
=> ["1,2,1,4,1,2,3\n"]
See the above example, how the ruby interpreter took all your elements as a single string and put it in an array as a single array element. So you need to explicitly convert the input to an array with comma as a delimiter. The below will address both your questions.
array = gets.chomp
array = array.split(',').map(&:to_i)
if array.uniq.length == array.length
puts "array does not contain duplicates"
else
puts "array does contain duplicates"
print array.select{ |x| array.count(x) > 1}.uniq!
end