I need to store a random number within a variable cycle of an indeterminate total of a list, I have as input parameters, the total of the list and the cycle. This is the code that I programmed and I know it's over elaborated, and that's the point, I want to optimize it.
puts 'KABUUM!!!'
total = gets.chomp.to_i
ciclo = gets.chomp.to_i
ciclos = total / ciclo
resto = total % ciclo
c = 0
z = ciclo * ciclos + 1
for x in 1..ciclos do
linea = ''
for y in 1..ciclo do
r = rand(100..999)
linea << ',' if linea != ''
linea << r.to_s
end
puts linea
end
if resto > 0
linea = ''
for n in z..total do
r = rand(100..999)
linea << ',' if linea != ''
linea << r.to_s
end
puts linea
end
this is a sample of three outputs:
D:\Sites\ruby>
D:\Sites\ruby>ruby ciclo.rb
KABUUM!!!
25
5
410,457,482,924,302
575,411,616,708,597
558,507,508,349,594
427,536,920,915,941
726,910,492,558,176
D:\Sites\ruby>ruby ciclo.rb
KABUUM!!!
24
5
635,194,107,247,770
814,435,570,986,554
602,225,357,117,144
594,292,960,814,602
488,412,571,990
D:\Sites\ruby>ruby ciclo.rb
KABUUM!!!
26
5
245,141,736,288,941
221,687,762,562,377
447,577,304,316,641
184,384,439,307,420
407,664,726,875,752
287
D:\Sites\ruby>
the friend @gerry helped me with a code that works perfect for consecutive numbers, but I do not know how to add the random to this code:
puts 'KABUUM!!!'
total = gets.chomp.to_i
ciclo = gets.chomp.to_i
(1..total).each_slice(ciclo) do |linea|
puts linea.join(",")
end