按百分比标准分发学生

时间:2014-06-25 15:28:48

标签: ruby-on-rails ruby

我的标准值是百分比。

criteria = {"Top" => 20, "Excellent" =>  30, "Average" => 30, "Poor" => 20 

我有学生哈希。键是学生ID,值是学生分数

students = { 1 => 80,
             2 => 90,
             3 => 30,
             4 => 50,
             5 => 120,
             6 => 90,
             7 => 50,
             8 => 50,
             9 => 50,
             10 => 30}

Crietria由老师添加。学生名额是这样计算的,因为我不能得到例如2.5名学生:

students_positions = criteria.map {|k, v| (students.count * (v.to_f/100)).ceil }
f=> [2, 3, 3, 2]

我做的第一件事就是根据学生的价值(分数)对学生进行分类

sorted_students = students.sort {|a1,a2| a2.last <=> a1.last }.to_h
=> {5=>120, 2=>90, 6=>90, 1=>80, 8=>50, 4=>50, 7=>50, 9=>50, 3=>30, 10=>30}

结果应该是来自学生哈希的学生的20%(2个学生职位)获得&#39; Top&#39;标准,30%(3个学生职位)得到&#39;优秀&#39;如果两个学生的分数相同,但是按照不同的标准分组,则两个学生都应该在之前的critera组中。例如,One在Top中得分为90而其他在Execellent中得分为90,第二个必须被移到Top crietria组。

我如何按标准分割学生

祝你好运, 的Georgi

1 个答案:

答案 0 :(得分:1)

将给定表达式(第一个不是Ruby表达式)修改为Ruby表达式:

criteria = {"Top" => 20, "Excellent" =>  30, "Average" => 30, "Poor" => 20}
students = {
  1 => 80,
  2 => 90,
  3 => 30,
  4 => 50,
  5 => 120,
  6 => 90,
  7 => 50,
  8 => 50,
  9 => 50,
  10 => 30
}

将值转换为有用的东西:

n = 0
accumulated_counts =
criteria
.each_with_object({}){|(k, v), h| h[k] = n += students.length * v / 100.0}

# =>
# {
#   "Top"       => 2.0,
#   "Excellent" => 5.0,
#   "Average"   => 8.0,
#   "Poor"      => 10.0
# }

students_by_score =
students.group_by(&:last).sort.reverse.map{|a| a.last.map(&:first)}

# => [[5], [2, 6], [1], [4, 7, 8, 9], [3, 10]]

分发学生:

n = 0
accumulated_counts
.each_with_object(Hash.new{|h, k| h[k] = []}) do |(k, v), h|
  h[k].push(*students_by_score.shift) while n + h[k].length < v
  n += h[k].length
end

# =>
# {
#   "Top"       => [5, 2, 6],
#   "Excellent" => [1, 4, 7, 8, 9],
#   "Average"   => [],
#   "Poor"      => [3, 10]
# }