开发者

How can I convert this to return multiple items?

I have a list of games, which I need to select randomly, by the day of week, the following code works perfectly for 1 game.

   var gameOfTheDay = games.AllActive[(int)(DateTime.Today.GetHashCode()) % games.AllActive.Count()]; 

What I need is to return more then 1 game, randomized, based on X ( X in the case above is the day of the week, I will change it to a specific string )

I need this to create a semi-random generation of items.

Semi - since I want to feed it a keyword,开发者_开发知识库 and get the same results Per keyword

Random - since I need to make the game list random

For example, every time you enter Page with title "hello", you will see THE SAME games, that were selected specificly for that keyword from the games list based on the keyword "hello".

In the same way the gameOfTheDay Works.


You can use LINQ for this:

int limit = 10;
string keyword = "foo";

Random rng = new Random(keyword.GetHashCode());
var gamesOfTheDay = games.OrderBy(x => rng.Next()).Take(limit);

However, this will have some overhead for the sort. If you have a lot of games compared to the amount you're selecting—enough that the sort might be too expensive, and enough that it's safe to just keep retrying in the event of a collision—manually doing it might be faster:

HashSet<Game> gamesOfTheDay = new HashSet<Game>();

while(gamesOfTheDay.Count < limit && gamesOfTheDay.Count < games.Length)
{
    int idx = rng.Next(games.Length);
    gamesOfTheDay.Add(games[idx]);
}

Note that in either case the Random is constructed with a seed dependent on the keyword, so the order will be the same every time for that keyword. You could similarly combine the hashes of the current DateTime and the keyword to get a unique random sequence for that day-keyword combination.


Use similar code to what you have now to randomly add games to a list of games (which will initially be empty) - if the game is already in the list, don't add it.

Stop when the list is the right size.

Untested code:

var rand = new Random();
var randomGames = new List<game>();
while(randomGames.Count < limit)
{
   var aGame = games.AllActive[rand.Next(limit)];
   if (!randomGames.Contains(aGame))
   {
      randomGames.Add(aGame);
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜