【问题标题】:Using a while Loop to iterate on an Array [closed]使用while循环迭代数组[关闭]
【发布时间】:2013-11-30 09:56:07
【问题描述】:

我正在尝试使用这个 while 循环来遍历我的数组以找到我的数组中的最小数字。想法?

array_2=[]
test_scores=[75, 100, 85, 65, 84, 87, 95, 99, 200]


while test_scores.count > 1
  if test_scores[1] > test_scores[0]
    array_2.push(test_scores[0])
    test_scores.count
  elsif
    total_scores[0] < test_scores[1]
      array_2.push(test_scores[1])
      test_scores.count
  elsif 
    test_scores.count==1
    break
  end
end

【问题讨论】:

    标签: ruby arrays while-loop


    【解决方案1】:

    你为什么不用Enumerable#min

    test_scores = [75, 100, 85, 65, 84, 87, 95, 99, 200]
    test_scores.min
    # => 65
    

    test_scores 没有改变。 test_scores.count &gt; 1 始终是 truewhile 循环没有结束。

    并且代码仅比较第一个元素 (test_scores[0]) 和第二个元素 (test_scores1)。

    【讨论】:

    • 我可以,但我仍然很好奇为什么它没有运行......有什么想法吗?
    • @user2980721,我添加了为什么代码没有给你想要的东西的原因。
    • 但是当 test_array==1 时它不应该最终还是会中断吗?
    • @user2980721,你的意思是test_array.count == 1吗? test_array.count 不会改变,因为test_array 本身不会改变。
    • @user2980721,将p test_array放入while循环中,然后运行;那么,你就会明白了。
    【解决方案2】:

    我认为你把算法复杂化了。假设您不想使用 Ruby 的 Enumerable#min,那么总体目标是什么?如果您正在寻找一个最小值,那么您将返回一个变量。您必须检查数组中的所有值,所以类似下面的内容不是更容易理解吗?

    minimum_value = nil
    test_scores.each {|num| minimum_value = num if minimum_value.nil? or num < minimum_value}
    

    本质上将 minimum_value 设置为 nil 会增加一个极端情况,如果 test_scores 中没有存储值。 each 只是迭代 test_scores 中的每个值(依次调用它的每个成员 'num'),然后将 minimum_value 设置为第一个数字或小于当前值的任何数字。

    【讨论】:

    • minimum_value = test_scores[0]; test_scores.each {|num| minimum_value = num if num &lt; minimum_value} 怎么样?
    • 我来自 c++ 背景,所以我习惯于 null/nil,尽管如果 test_scores 是一个空白数组,显然 Ruby 会自动为 nil。
    猜你喜欢
    • 1970-01-01
    • 2021-10-31
    • 2010-09-11
    • 2016-07-27
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 2016-06-07
    相关资源
    最近更新 更多