【问题标题】:Counting amount of times element appears in array计算元素出现在数组中的次数
【发布时间】:2016-09-16 05:04:14
【问题描述】:

我是在 Stackoverflow 上发帖的新手,但我在搞清楚一些事情时遇到了很多麻烦。我是红宝石语言的新手。

我想计算数组中某个元素大于特定常数的次数。数组长度在 10 到 25 之间,由用户选择。然后我将数组从大到小排序。我想计算数组中某个值大于或等于 35 的次数。这将定义为常量“配额”

 puts "Enter a number between 10 and 25 to represent the number of users: "
num = gets.to_i
if num > 25 or num < 10
  puts "I said between 10 and 25. Try again"
    num = gets.to_i
end
homeDir = Array.new(num) { rand(20..50)}
homeDir.sort!{|x,y| y<=>x}
puts  homeDir
quota = 35

【问题讨论】:

    标签: arrays ruby count scripting


    【解决方案1】:

    你可以使用方法count

    homeDir.count{|el| el >= 35 }
    

    【讨论】:

    • 感谢您的帮助。我最终写了这个解决了我的问题。配额 = 35 homeDir.each |x| puts x} homeDir.each 做 |y| if y > quota counter = counter + 1 end end
    【解决方案2】:

    这是我的问题解决了。

    print  "Enter a number between 10 and 25 to represent the number of users: "
    num = gets.chomp.to_i 
    while num > 25 or num < 10
      print "I said between 10 and 25. Try again: " 
        num = gets.to_i 
    end
    homeDir = Array.new(num) { rand(20..50)} 
    homeDir.sort!{|x,y| y<=>x} 
    
    quota = 35
    counter = 0
    puts"\n"
    puts "Directory Sizes (in MB)"
    puts "======================"
    
    homeDir.each{|x| puts x} 
    homeDir.each do |y| 
      if y > quota
        counter = counter + 1
      end
    end
    puts "\n"
    puts "There are #{counter} users whos directories are over 35MB"
    

    【讨论】:

    • 1.第 2 行在 each 之后需要一个左大括号 ({)。 2.您需要将counter初始化为零。 3.if必须与end配对(或写counter = counter + 1 if y &gt; quota。4.效率低,因为它没有利用homeDir已排序的事实。总是在发布之前测试你的代码。这是不是类似 Ruby 的代码,而是反映了一种过程方法。
    • 对不起,这是我第一个学红宝石的学期。当我回答我自己的问题时,我无法从我的虚拟机中复制和粘贴代码,所以我将其输入。感谢您抓住它,我将编辑上面的帖子。
    【解决方案3】:

    由于homeDir 从大到小排序,因此使用Array#take_while(然后使用Array#size)通常比使用Array#count 更有效,因为count 必须遍历整个数组。

    def count_biggest(arr, num)
      arr.take_while { |n| n >= num }.size
    end
    
    arr = [5,4,3,2,1]
    
    count_biggest(arr, 3) #=> 3
    count_biggest(arr, 6) #=> 0
    count_biggest(arr, 0) #=> 5
    

    【讨论】:

      猜你喜欢
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多