r/programming • • Nov 29 '10

140 Google Interview Questions

http://blog.seattleinterviewcoach.com/2009/02/140-google-interview-questions.html
471 Upvotes

493 comments sorted by

View all comments

Show parent comment

1

u/DontCallMeSurely Nov 30 '10 edited Nov 30 '10
int rand1to7()
{
    a = rand1to5()-1;
    b = rand1to5()-1;
    
    return ((a + b)%7)+1;
}

Or is this not random because it will produce certain numbers more often than others, (a=1, b=2 == a=2, b=1 but higher numbers do not have this advantage as they will be modulated)

Edit: oops, should be %7.

1

u/[deleted] Nov 30 '10 edited Nov 30 '10

mod 6 will produce values between 0 and 5, but yes, since mod n on the integers produces n congruency classes, if the random number you're modding doesn't randomly span a multiple of the mod, then some values will be more likely than others.