user5547731
user5547731

Reputation:

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

Upvotes: 1

Views: 119

Answers (2)

A. Saloff
A. Saloff

Reputation: 71

#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}"

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

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.

Upvotes: 2

Related Questions