Ruby的each方法逻辑问题

6

我正在尝试解决来自七周七语言的一个简单的Ruby问题。

使用each仅打印十六个数字数组的内容,每次四个数字。

这是我想出的方法,有更简单或更好的方法吗?

a = (1..16).to_a

i = 0
j = []
a.each do |item|
  i += 1 
  j << item
  if(i % 4 == 0)
    p j
    j = []
  end
end

可以使用each_slice在一行中完成

a.each_slice(4){|x| p x}

8个回答

6

Teja,你的解决方案是可以的。由于你需要使用每个元素,因此算法复杂度将受到数组大小的限制。

我想出了下面的解决方案。它与你的想法相同,只是不使用辅助变量(j)来存储部分结果。

i = 0
a.each do |item|
  p a[i, 4] if(i % 4 == 0)
  i +=1
end

不错。这是唯一不使用辅助变量的解决方案。谢谢。 - Teja Kantamneni
问题指定了使用 each,但没有说明它必须用在哪个数组上! - glenn mcdonald

2

格伦·麦克唐纳的代码很短,但它使用了不被允许的切片(只能使用each,请记住)。这是我的代码:

(0...a.size).each {|index| p a[index, 4] if index % 4 == 0}

这个方法同样适用于其他数组大小,这里以一个大小为18的数组为例:

>> a = (113..150).to_a.insert(5,55).insert(10,66666).shift(18)
=> [113, 114, 115, 116, 117, 55, 118, 119, 120, 121, 66666, 122, 123, 124, 125, 126, 127, 128]
>> (0...a.size).each {|index| p a[index, 4] if index % 4 == 0}
[113, 114, 115, 116]
[117, 55, 118, 119]
[120, 121, 66666, 122]
[123, 124, 125, 126]
[127, 128]
=> 0...18

1

我认为这应该适用于任何大小的数组和任何块大小x:

x = 4
(0...(a.size/x.to_f).ceil).each {|i| p a.slice(x*i,x)}

0

试试这个:

(1..16).each do |item|
  print "#{item} "
  print "\n" if item % 4 == 0
end

我曾考虑过这个问题,但是题目要求每次打印四个数字,而这个解决方案打印一个数字并添加换行符号,这可能不是他们要求的解决方案。 - Teja Kantamneni

0
问题没有说明十六个数字的数组是连续的或从一开始...让我们创建一个适用于任何16个数字的解决方案
##########
# Method 1 - Store chunks of 4 and print at the end
##########
a = (1..16).to_a
b = []
a.each do |item|
    b << [] if b.size == 0
    b << [] if b[-1].size == 4
    b[-1] << item
end

# choose your desired printing method
print b 
b.each{|c| puts c.join(",")}

##########
# Method 2 - print the chunks as they are encountered
##########

# Note: "p" was specifically chosen over "print" because it returns the value printed instead of nil.
#       If you use a different printing function, make sure it returns a value otherwise the 'b' array will not clear.


# Note: This implementation only prints out all array entries if a multiple of 4
#       If 'b' contains any items outside the loop, they will not be printed
a = (1..16).to_a
b = []
a.each do |item|
    b << item
    b = [] if b.size == 4 and puts b
end


# Note: This implementation will print all array elements, even if number of elements is not multiple of 4.
a = (1..16).to_a
b = []
a.each do |item|
    b = [] if b.size == 4 and p b
    b << item
end
p b

0

我使用了类似于Miguel的东西,尽管他的更加简洁:

array = (1..16).to_a
i = 0
array.each do
  puts array[i...i+4].to_s if i % 4 == 0 and i+4 <= array.size
  i+=4 
end

0

你被禁止使用each_with_index吗?如果没有,可以在@Miguel的答案基础上构建:

a.each_with_index do |item, i|
  p a[i, 4] if i.modulo(4).zero?
end

我还将 i % 4 == 0 替换成了一些听起来像英语的东西(“i模4等于零”)


0

不使用切片的一行代码:

a.each {|i| p a[i,4] if (i+3) % 4 == 0}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接