我想将迭代中的当前元素与数组中的其余元素进行比较。从起点我没有问题。当我想要将当前元素与数组中背后的元素进行比较时,问题就出现了。
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
我正在寻找类似的东西:
"3 is greater than 1 and 2 but less than 4 and 5"
有什么想法吗?
答案 0 :(得分:2)
我假设您希望比较数组中的所有元素,因此您可以通过使用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
您可以使用格式化输出,但这会给出:
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 []
答案 1 :(得分:1)
partition
个分组将元素分成两个独立的组。
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
答案 2 :(得分:0)
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]}" }
打印
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 []