Generating random pairs in C #
I have a table in my DB with a list of people. I need to create a list of random friends every day.
The idea is that every day each person is connected to another random person on that day.
Since the table can get very large, I was wondering what would be the best way to do such a thing?
I've thought of two ideas, but I'm not sure about them regarding performance.
1) I am using a random number generator to randomly select two IDs. The problem is that I have to constantly make sure that the numbers have not been called yet, and as I get closer to the end of the list, this can get very slow.
2) start each with the guy below them on the list and just work your way down every day until you get to the end, at which point I get back to the top.
Any other ideas?
thanks
a source to share
Actually it's not that hard using a random generator, not very slow, but if you are very unlucky the time complexity becomes O (n ^ 2) and at best O (1) as you like
However, you have a table that connects two persons, see if their ids are fast, if not, just add their ids, use T-SQL to free up additional connections.
a source to share
It seems to me that this problem has already been solved.
- You want to create lists of pairs.
- You need all pair lists (one for each day)
You don't need to use a random function for this. You just need to generate all the pairs lists.
The Permutation page on Wikipedia contains several implementations of the algorithm you need to use.
#!/usr/bin/perl -w
use strict;
use warnings;
use Data::Dumper;
sub permutation {
my ($k, $s) = @_;
for my $j (1..(@$s-1)) {
my $n = ($k % $j) + 1;
($s->[$n], $s->[$j]) = ($s->[$j], $s->[$n]);
$k = int($k / $j);
}
return $s;
}
for (1..3) {
my $s = permutation($_, [1,2,3,4]);
my ($a, $b, $c, $d) = @$s;
print "$a\t$b\n";
print "$c\t$d\n";
print "------\n";
}
a source to share