0

Hi can anybody explain to me how i can convert this code in ruby to vb.net cause i think this is what i need. I am trying to divide a number into as equal as possible parts.

If all parts cant be equal because the numbers cant be divided by eachother ex. 32 div by 3. The result of this should give me 11, 11 and 10 this is as equal as possible.

I found some code here that does this Split number into equal parts or what's closest to that

def split_into n, p
    [n/p + 1] * (n%p) + [n/p] * (p - n%p)
end

print (split_into 32, 3) # => [11, 11, 10]

So now i have the issue that i do not understand whats happening here in ruby and so am unable to convert it.

Thanks for any help in advance.

arnekick
  • 43
  • 7
  • `dim result = Enumerable.Range(1, n mod p).Select(Function(s) n \ p + 1).Concat(Enumerable.Range(1, p - n mod p).Select(Function(s) n \ p)).ToArray()` – Jimi May 10 '23 at 11:25

1 Answers1

5

i do not understand whats happening here in ruby and so am unable to convert it

I'll try to explain what's going on so you can convert it.

When dividing 32 by 3 using Euclidean division you have:

32 = 3 × 10 + 2

With 10 being the quotient and 2 being the remainder.

Or more general:

a = d × q + r

To get 3 "equal" parts, you have to distribute those 2:

32 = 11 + 11 + 10
   = 2 × 11 + 1 × 10
   = 2 × (10+1) + (3-2) × 10

Or more general:

a = r × (q+1) + (d-r) × q

In Ruby, these parts can be expressed as:

[11] * 2 + [10] * 1
#=> [11, 11, 10]

In the above, [11] is an array and * duplicates its content, i.e. [11] * 2 is [11, 11]. The same happens for [10] * 1 which is just [10]. Finally, both arrays are concatenated via +, i.e. [11, 11] + [10] which returns [11, 11, 10].

Or more general:

a = 32
d = 3
q = a / d #=> 10
r = a % d #=> 2

[q+1] * r + [q] * (d-r)
#=> [11, 11, 10]

Compare the above with your [n/p + 1] * (n%p) + [n/p] * (p - n%p) and you'll see that it's equivalent (n is a, p is d, n/p is q and n%p is r).

Without array operators, you could use two loops to add the 11's and 10's:

parts = []

r.times { parts << q+1 }
(d-r).times { parts << q }

parts #=> [11, 11, 10]
Stefan
  • 109,145
  • 14
  • 143
  • 218