best process and loop in Ruby with a random

0

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
    
asked by rrg1459 29.09.2017 в 15:19
source

1 answer

1

You can use the same code that I gave you but generating the random before converting the linea to a string , and this can be generated with the < a href="https://ruby-doc.org/core-2.4.2/Array.html#method-i-map"> Array # map ; for example:

puts 'KABUUM!!!'

total = gets.chomp.to_i
ciclo = gets.chomp.to_i

(1..total).each_slice(ciclo) do |linea|
  puts linea.map { |_| rand(100..999) }.join(",")
end
  • map executes the code provided in the block for each element (available in the variable _ ) of the collection and returns an array with the result.
  • The variable _ takes that name since in your block no it is being used, however you need to specify it since map will always give you the variable; the Ruby community recommends calling those variables that are not used with _ to identify them, although you could name them as you want.
answered by 29.09.2017 / 15:49
source