user3007294
user3007294

Reputation: 951

Compare current element to the remaining in Array (Ruby)

I want to compare the current element inside an iteration to the rest of the elements in the array. I have no issues from the starting point. The issue comes when I am looking to compare the current element to the elements behind it inside the array.

array = [1, 2, 3, 2, 3, 4, 5]


array.each_with_index do |num, index|
  break if array[index + 1] == nil
  if num > array[index + 1]
    puts "#{num} is greater than the #{array[index + 1]}!"
  else 
    puts "#{num} is less than the #{array[index + 1]}!"
  end
end 

I am looking for something like:

"3 is greater than 1 and 2 but less than 4 and 5"

Any ideas?

Upvotes: 0

Views: 247

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110665

arr = [1, 2, 3, 2, 3, 4, 5]

a = arr.uniq.sort
  #=> [1, 2, 3, 4, 5] 
h = a.each_with_index.to_h
  #=> {1=>0, 2=>1, 3=>2, 4=>3, 5=>4} 

arr.each { |i| puts "#{i} is greater than #{a[0,h[i]]} but less than #{a[h[i]+1..-1]}" }

prints

1 is greater than [] but less than [2, 3, 4, 5]
2 is greater than [1] but less than [3, 4, 5]
3 is greater than [1, 2] but less than [4, 5]
2 is greater than [1] but less than [3, 4, 5]
3 is greater than [1, 2] but less than [4, 5]
4 is greater than [1, 2, 3] but less than [5]
5 is greater than [1, 2, 3, 4] but less than []

Upvotes: 0

drunkel
drunkel

Reputation: 228

I'm assuming you want all of the elements in the array compared, so you could do something like the following, by making use of Array#select:

array = [1, 2, 3, 2, 3, 4, 5]
filtered_array = array.uniq

array.each do |i|
  greater_than = filtered_array.select { |comp| comp < i }
  less_than = filtered_array.select { |comp| comp > i }

  puts "#{i} is greater than #{greater_than} but less than #{less_than}"
end

You could play with formatting the output, but this would give:

1 is greater than [] but less than [2, 3, 4, 5]
2 is greater than [1] but less than [3, 4, 5]
3 is greater than [1, 2] but less than [4, 5]
2 is greater than [1] but less than [3, 4, 5]
3 is greater than [1, 2] but less than [4, 5]
4 is greater than [1, 2, 3] but less than [5]
5 is greater than [1, 2, 3, 4] but less than []

Upvotes: 2

kcdragon
kcdragon

Reputation: 1733

partition breaks divides up the elements into two separate groups.

array = [1,2,3,4,5]
array.each do |n|
  less_than, greater_than = *(array - [n]).partition { |m| m <= n }
  text = []
  text << "is greater than #{less_than.join(', ')}" if less_than.count > 0
  text << "is less than #{greater_than.join(', ')}" if greater_than.count > 0
  puts "#{n} #{text.join(' and ')}"
end

Upvotes: 1

Related Questions