jeudi 1 septembre 2016

Rails 4: using offset on a randomized list produces unexpected results

...or maybe, i just don't get it.

TL;DR - i get totally randomized results with duplicates and such. No idea why.

Here's the problem - i'm trying to make a rails app generating tournament brackets. The user can select whether he'd like to randomize the team list when generating the bracket, or later assign the teams by himself.

If i choose the latter option and generate the bracket as the ids go, everything is fine. If i choose to randomize the list, the list itself is fine, but later when assigning teams to particular matches (in a loop), the resulst are completely unorganized and unexpected (at least to me) eg.

instead of
Match 1: Team 1 vs Team 2
Match 2: Team 3 vs Team 4
etc. (as in the normally generated list)

i get something completely random with frequent duplicates like:
Match 1: Team 1 vs Team 1
Match 2: Team 1 vs Team 9

if @seed = 'random'
  @team_list = @tournament.teams.order("RAND()")
else
  @team_list = @tournament.teams.order(:id)
end

Here's how i assign the teams. The thing that screws everything up seems to be the "offset" part, and i don't get it, why.

@match.team_a = @team_list.offset((2*match_number)-2).limit(1).first               
@match.team_b = @team_list.offset((2*match_number)-1).limit(1).first




Aucun commentaire:

Enregistrer un commentaire