Sonny Black
Sonny Black

Reputation: 1617

How do I split arrays using a while loop?

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.

Upvotes: 0

Views: 276

Answers (5)

Cary Swoveland
Cary Swoveland

Reputation: 110675

Assuming you want to preserve order, as in your example:

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]

If you want to preserve order and have the first subarray contain nbr elements, add this:

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]

Upvotes: 0

hirolau
hirolau

Reputation: 13901

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

p small, large 
#=> [6, 9, 17, 18, 23]
#=> [32, 45, 48, 65, 88, 97]

Upvotes: 4

Bala
Bala

Reputation: 11234

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]

Another variation

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]

Upvotes: 0

vogomatix
vogomatix

Reputation: 5041

Don't use a while loop - sort the array and then split it in two

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


a.sort.each_slice( a.size/2) probably does the trick without rails.

Upvotes: 0

sabrams
sabrams

Reputation: 1128

Try this:

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

It will give you an array containing your split array:

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

In this case, if you have an odd number of elements in your array, the first array returned will always have the extra element. You can also save the arrays separately if you would like, but this way you can call each of the halves with newarray[0] and newarray[1]. If you want to split them simply add:

b = newarray[0]
c = newarray[1]

Upvotes: 2

Related Questions