2016-08-25 39 views
0

我想将迭代中的当前元素与数组中其余元素进行比较。从起点看,我没有任何问题。这个问题出现在我想要比较当前元素与后面的元素之内。比较当前元素和剩余的数组(Ruby)

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

剩余*(前意后)。好的赶上(我更新了标题) – user3007294

回答

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 [] 
+0

谢谢drunkel!有趣的解决方案,但它工作! – user3007294

+0

由于'array.uniq'不会改变'arr','dup'没有任何用处。对于每个'i',编写'ndx' ='sorted_array.index(i); less_than = sorted_array [0..ndx-1]; greater_than = sorted_array [ndx + 1 ..- 1]'。对于表示数组元素的块变量,“i”不是一个好的选择,因为它通常用于引用索引。 –

+0

@CarySwoveland [正确](https://ruby-doc.org/core-2.2.0/Array.html#method-i-uniq),谢谢! 'sort'也不能真正帮助这个实现。我已经更新了解决这两个问题的答案。 – drunkel

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 
+0

谢谢kcdragon!直到现在我还不熟悉分区。我已经实施了drunkel的解决方案,但给了它一个upvote的建议! – user3007294

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 []