计算元素的次数出现在数组中

时间:2016-09-13 15:06:05

标签: arrays ruby count scripting

我是新手在Stackoverflow上发帖但我在搞清楚方面遇到了很多麻烦。我是红宝石语言的新手。

我想计算数组中元素大于特定常量的次数。阵列长度在10到25之间,由用户选择。然后我将数组从最大到最小排序。我想计算一个数组中的值大于或等于35的次数。这将被定义为常量" Quota"

 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

3 个答案:

答案 0 :(得分:0)

您可以使用方法count

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

答案 1 :(得分:0)

由于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

答案 2 :(得分:0)

这是我的问题解决了。

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"