How to re-create (each time create new) array in Ruby? - arrays

What I missing for create new array for each pair of numbers and then put the sum of each pair? Btw, is it possible to enter pair of numbers through ',' on one line?
arr = []
sum = 0
puts "How much pair of numbers do you want to sum?"
iter = gets.to_i
iter.times do |n|
puts "Enter pair of numbers: "
a = gets.to_i
b = gets.to_i
arr << a
arr << b
end
iter.times do |n|
puts "Here are the sums: "
arr.each { |x| sum += x }
puts sum
end
The input must be like this:
2 # Number of pairs
562 -881 # First pair
310 -385 # Second pair
So the output will be:
-319
-75

For the first part of your question you modify your code like this:
arr = []
sum = 0
puts "How much pair of numbers do you want to sum?"
iter = gets.to_i
iter.times do |n|
puts "Enter pair of numbers: "
a = gets.to_i
b = gets.to_i
arr << [a, b] # store a new 2-element array to arr
end
iter.times do |n|
puts "Here are the sums: "
arr.each { |a, b| puts a + b } # calculate and output for each
end
For the second part of your question, you can do:
a, b = gets.split(',').map(&:to_i)
and rework the calculation/output part like this (with just one loop):
puts "Here are the sums: "
arr.each { |a, b| puts a + b } # calculate and output for each
plus some error handling.

Related

Getting nil error when adding elements in Array - Ruby

I am trying to get a number from the user, store this number in the array and then add everything in the array together to display a total.
names = Array.new(20)
sum = 0
x = 0
for index in 0..5
puts "Enter a number: "
data = gets.to_i
names.push data
x = x + names[index]
end
puts x
But I am getting the error rb:10:in `+': nil can't be coerced into Integer (TypeError)
I guess its not allowing me to add whatever is in the array together. Anybody know a workaround for this?
There are some issues with your code.
Array.new(20) – you probably think this creates an array of the given size. Well, it does, but it also fills the array with a default object of nil:
Array.new(3)
#=> [nil, nil, nil]
In Ruby, you just create an empty array. It will grow and shrink automatically. And instead of Array.new you can use an array literal:
names = []
for index in 0..5 – for loops are very unidiomatic. You should use one of these:
(0..5).each do |index|
# ...
end
0.upto(5) do |index|
# ...
end
6.times do |index|
# ...
end
And finally:
names.push data
x = x + names[index]
You are pushing an element to the end of the array and then fetch it from the array using an absolute index. This only works if index and array size correlate exactly.
It's more robust to either use an explicit index for both, storing and fetching:
names[index] = data
x = x + names[index]
or to fetch the last element: (note that index isn't needed)
names.push data
x = x + names.last
Ruby also provides negative indices that are relative to the array's end:
names.push data
x = x + names[-1]
Needless to say, you could just omit the fetching:
names.push data
x = x + data
It might be useful to separate the data gathering from the calculation:
numbers = []
6.times do
puts 'Enter a number: '
numbers << gets.to_i
end
and then:
numbers = [1, 2, 3, 4, 5, 6] # <- example input
numbers.sum
#=> 21
# -- or --
numbers.inject(:+)
#=> 21
# -- or --
sum = 0
numbers.each { |n| sum += n }
sum
#=> 21
You are initializing the array with 20 nil names. Then you push the first entered number to the array (position 21) and try to concat the position [0] (names[0]) that is nil.
Try to change the first line:
names = Array.new

I have a problem with 2D arrays in RUBY where it doesn't assign the values into it

PLAYERS = 4
def input(noteam, arraya)
for x in 0..noteam-1
for y in 0..PLAYERS-1
arraya[x] = Array.new(PLAYERS)
puts "Team " + (x+1).to_s
arraya[x][y] = read_integer("Enter score for individual player " + (y+1).to_s)
end
end
end
def disp_arr(myarray, row, col)
print myarray[0]
for x in 0..row-1
for y in 0..col-1
print myarray[x][y]
end
end
end
def main
notm = read_integer("How many teams:")
arraya = Array.new(notm)
input(notm, arraya)
disp_arr(arraya, notm, PLAYERS)
end
main #=> invoking the main method
So I tried doing print myarray[0] for the first row and [nil,nil,nil,10] comes out so I know that there's a problem with assigning the value into the array but I'm not too sure whats wrong with it.
Move line arraya[x] = Array.new(PLAYERS) out of internal for loop
def input(noteam, arraya)
for x in 0..noteam-1
arraya[x] = Array.new(PLAYERS) # <-
puts "Team #{x + 1}"
for y in 0..PLAYERS-1
puts "Player: #{y + 1}"
arraya[x][y] = read_integer("Enter score for individual player " + (y+1).to_s)
end
end
end
Your original code reset arraya[x] to new array for every team player except last.
That is why you observing [nil, nil, nil, 45] result, because only last player results being saved.

Counting amount of times element appears in array

I am new to post on Stackoverflow but I am having lots of trouble figuring something out. I am new to the ruby language.
I would like to count the amount of times an element in the array is greater than a specific constant. The array length is between 10 and 25, this is chosen by the user. I then have the array sorted from largest to smallest. I would like to count the amount of times a value in the array is larger or equal to 35. This will be defined as the constant "Quota"
puts "Enter a number between 10 and 25 to represent the number of users: "
num = gets.to_i
if num > 25 or num < 10
puts "I said between 10 and 25. Try again"
num = gets.to_i
end
homeDir = Array.new(num) { rand(20..50)}
homeDir.sort!{|x,y| y<=>x}
puts homeDir
quota = 35
you can use method count
homeDir.count{|el| el >= 35 }
This is my question solved.
print "Enter a number between 10 and 25 to represent the number of users: "
num = gets.chomp.to_i
while num > 25 or num < 10
print "I said between 10 and 25. Try again: "
num = gets.to_i
end
homeDir = Array.new(num) { rand(20..50)}
homeDir.sort!{|x,y| y<=>x}
quota = 35
counter = 0
puts"\n"
puts "Directory Sizes (in MB)"
puts "======================"
homeDir.each{|x| puts x}
homeDir.each do |y|
if y > quota
counter = counter + 1
end
end
puts "\n"
puts "There are #{counter} users whos directories are over 35MB"
Since homeDir is sorted largest to smallest, it would generally be more efficient to use Array#take_while (and then Array#size) than Array#count, as count must traverse the entire array.
def count_biggest(arr, num)
arr.take_while { |n| n >= num }.size
end
arr = [5,4,3,2,1]
count_biggest(arr, 3) #=> 3
count_biggest(arr, 6) #=> 0
count_biggest(arr, 0) #=> 5

Ruby trouble with arrays and sorting

How can I count the amount of integers before that input and after.
user_array = user_input.chars.to_a
user_array.map {|item| item.to_i}
num = gets.to_i
arrange_array = user_array.push(num).join(",")
#need to give number before, and number after input
puts "Please enter some numbers:"
user_input = gets.chomp
puts "Please enter another number:"
num = gets.to_i
user_input.split('')
.map(&:to_i) # convert them to integers
.partition { |n| n < num } # split / partition by cond
.map(&:sort) # sort results
#⇒ [[0, 1, 2], [4, 5]]
The core of this solution is Enumerable#partition method, that splits the array by the condition provided.
#ENTER ARRAY OF NUMBERS
puts "Please enter some numbers: "
user_input = gets.chomp
user_array = user_input.chars.to_a
user_array.map! {|item| item.to_i}
# important to ad the ! to the map method
#ENTER NUMBER
puts "Please enter another number: "
num = gets.to_i
user_array << num
user_array.sort!
amount_before = user_array.index(num)
amount_after = user_array.count - user_array.index(num) - 1
puts "There are #{amount_before} integers before #{num}, and #{amount_after} integers after #{num}"

Sum in Ruby array

I'm trying to do a program that asks the user for three numbers one at a time, store them in array, then print the list of the numbers and the total.
Please explain.
Here is what I have so far:
numbers = Array.new
numbers = []
puts "Enter first number: "
first = gets.to_i
puts "Enter second number: "
second = gets.to_i
puts "Enter third number: "
third = gets.to_i
def sum(numbers)
return 0 if numbers.length < 1
result = 0
numbers.each { |num| result += num }
result
end
You can also use Array's reduce method.
http://ruby-doc.org/core-2.1.0/Enumerable.html#method-i-reduce
#!/usr/bin/ruby
numbers = Array.new
# numbers = [] #this is same as above
puts "Enter first number: "
first = gets.to_i
numbers<<first
puts "Enter second number: "
second = gets.to_i
numbers<<second
puts "Enter third number: "
third = gets.to_i
numbers<<third
puts numbers.reduce {|sum, n| sum + n } #here
Here is one more way of doing this:
sum = 3.times.collect{ |i| puts "Enter number #{i + 1}:"; gets.chomp.to_i }.inject(:+)
puts sum
Could also be written like below:
read_num = lambda{|i| puts "Enter number #{i}"; gets.chomp.to_i}
sum = 3.times.map(&read_num).reduce(:+)
puts sum
You haven't pushed any of your inputs into the array, you can either use the push function or the << to add elements to your array
#!/usr/bin/ruby
numbers = Array.new
numbers = []
puts "Enter first number: "
first = gets.to_i
numbers<<first
puts "Enter second number: "
second = gets.to_i
numbers<<second
puts "Enter third number: "
third = gets.to_i
numbers<<first
def sum(someArray)
return 0 if someArray.length < 1
result = 0
someArray.each { |num| result += num }
result
end
hope that helps
There are two problems here:
You aren't pushing the numbers you read into the array
You defined the sum function properly, but aren't calling it anywhere
#!/usr/bin/ruby
numbers = Array.new # note the second, redundant, initialization on numbers was removed
puts "Enter first number: "
(numbers ||= []) << gets.to_i # Pushing read value into the array (issue 1)
puts "Enter second number: "
(numbers ||= []) << gets.to_i # Here too
puts "Enter third number: "
(numbers ||= []) << gets.to_i # And here too
def sum(numbers)
return 0 if numbers.length < 1
result = 0
numbers.each { |num| result += num }
result
end
puts sum(numbers) # Calling sum (issue 2)

Resources