简体   繁体   English

将数组的元素与该数组中的其他元素匹配

[英]Match an element of an array to a different element in that array

I have an array containing several students. 我有一个包含几个学生的数组。 I want them to cross-grade one another randomly, ie each student will grade someone and will be graded by someone else (these two people may or may not be the same person). 我希望他们随机交叉评分,即每个学生将为某人评分,并由其他人评分(这两个人可能是或不是同一个人)。

Here is my close to working solution. 这是我接近的解决方案。 One big problem with this code is that the last person may have to grade himself if everyone else has been matched. 此代码的一个大问题是,如果其他所有人都匹配,则最后一个人可能必须对自己进行评分。

I am very interested in a working and more elegant solution. 我对一种可行且更优雅的解决方案非常感兴趣。

def randomize(student_array)
  graders = student_array.dup
  gradees = student_array.dup
  result = {}
  graders.each do |grader|
    gradee = grader
    while gradee == grader
      gradee = gradees.sample
    end
    result[grader] = gradee
    gradees.delete_at(gradees.index(gradee))
  end
  return result
end

If you don't have to pick up one from all possibilities but pick up a random case from limited cases, then it is easy. 如果您不必从所有可能性中选择一个,而是从有限情况中选择一个随机情况,那么这很容易。 For example, the following will give a match: 例如,以下将给出一个匹配项:

student_array = %i[a b c d e]
a = student_array.shuffle
[a, a.rotate(1)].transpose.to_h
# => {:b => :e, :e => :d, :d => :a, :a => :c, :c => :b}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM