0

I want to write a program that splits an array into two arrays, where any element in one array is smaller than any element in the other array.

The input that I have is:

a = [6, 45, 23, 65, 17, 48, 97, 32, 18, 9, 88]

And I'd like output like this:

[6, 23, 17, 18 , 9] < [45, 65, 48, 97, 32, 88]

I've tried:

i = 0
max = 0

while i < a.size
  if a[i] > max
    max = a[i]
  end
  i+=1
end

puts "this is the larger array: " + max.to_s

Which is completely off. As I am new to this, any help is appreciated.

4

5 回答 5

4
small, large = a.sort!.shift(a.size/2) ,a

p small, large 
#=> [6, 9, 17, 18, 23]
#=> [32, 45, 48, 65, 88, 97]
于 2013-11-14T20:27:34.517 回答
2

尝试这个:

newarray = a.sort.each_slice((a.size/2.0).round).to_a

它将为您提供一个包含拆分数组的数组:

newarray = [[6,9,17,18,23,32],[45,48,65,88,97]]

在这种情况下,如果数组中有奇数个元素,则返回的第一个数组将始终包含多余的元素。如果您愿意,您也可以单独保存数组,但这样您可以使用 newarray[0] 和 newarray[1] 调用每一半。如果要拆分它们,只需添加:

b = newarray[0]
c = newarray[1]
于 2013-11-14T20:08:54.253 回答
0

不要使用 while 循环 - 对数组进行排序,然后将其一分为二

a.sort
a.in_groups_of( a.size/2)


a.sort.each_slice( a.size/2) probably does the trick without rails.
于 2013-11-14T19:58:52.377 回答
0
a = [6, 45, 23, 65, 17, 48, 97, 32, 18, 9, 88]
a = a.sort
print a.shift(a.count/2), " < " , a 
#=> [6, 9, 17, 18, 23] < [32, 45, 48, 65, 88, 97]

另一种变化

a = [6, 45, 23, 65, 17, 48, 97, 32, 18, 9, 88]
a = a.sort
print a.values_at(0..a.count/2), " < ", a.values_at((a.count/2)+1 .. -1)
#=> [6, 9, 17, 18, 23] < [32, 45, 48, 65, 88, 97]
于 2013-11-14T20:13:45.740 回答
0

假设您想保留订单,如您的示例所示:

def split_it(a,n)
  f = a.select {|e| e <= n}
  [f, a-f]
end

a = [6, 45, 23, 65, 17, 48, 97, 32, 18, 9, 88]

f, l = split_it(a,23)
puts "#{f} < #{l}" # => [6, 23, 17, 18, 9] < [45, 65, 48, 97, 32, 88]

如果要保留顺序并让第一个子数组包含nbr元素,请添加:

def split_nbr(a, nbr)
  n = 1
  loop do
    return [] if n > a.max
    b = split_it(a,n)
    return b if b.first.size == nbr
    n += 1
  end   
end

f, l = split_nbr(a,3)
puts "#{f} < #{l}" # => [6, 17, 9] < [45, 23, 65, 48, 97, 32, 18, 88]
于 2013-11-14T20:05:47.840 回答