Home > OS >  Why does the Random class somtimes return nothing?
Why does the Random class somtimes return nothing?

Time:09-07

As you can see in my code down below, I have A and B. For example if I place the result at B then it sometimes return as result=0, nothing prints out in the console. But A works as it is expected to do. I don't really understand it, I did put a breakpoint, and stepped into the code but it didn't tell me much, just that the result return 0, this should infact print out the movie at Index 0? Sorry for being stupid, just want some clarification.

 private static void PickRandomMovie(List<Movie> movie)
    {
        var rng = new Random();

        //A:
        var result = rng.Next(0, movie.Count);

        for (int i = 0; i < movie.Count; i  )
        {
            //B:
            //var result = rng.Next(0, movie.Count);

            if (movie[i].Index.Equals(result))
            {
                Console.WriteLine(movie[i].Title);
                break;
            }
        }
    }

    private static List<Movie> AddMovie()
    {
        return new List<Movie>
        {
           new Movie(new Movie(0, "Shark Attack", "Horror, Thriller")),
           new Movie(new Movie(1, "Tom Clancy's", "Action")),
           new Movie(new Movie(2, "American Pie", "Comedy")),
           new Movie(new Movie(3, "Ted", "Comedy")),
           new Movie(new Movie(4, "Ted 2", "Comedy")),
           new Movie(new Movie(5, "American Pie 2", "Comedy")),
           new Movie(new Movie(6, "Tom Clancy's 2", "Action")),
           new Movie(new Movie(7, "Guardians of the Galaxy", "Comedy, Action")),

        };
    }

CodePudding user response:

A chooses a random number and then loops all items in your array looking for the one where Index matches your pre-selected random number

B loops the array of items picking a new random number on every iteration of the loop and only writes the result if it happens to match.

There is a fairly high chance that the B case will never hit a match

CodePudding user response:

While Jamiec explains the error well enough, I would suggest a few changes to your method:

  1. Remove the explicit index from the movie objects, objects might have an id, but should not know or care about how they are stored or what index they have.
  2. Don't loop thru the list, just do the indexing explicitly.
  3. You should probably separate the search of the random item, from the print to the console part. That will help make your functions reusable.
  4. There is no reason not to make such a function generic.

public static T PickRandomValue<T>(List<T> values, Random rng )
    => values[rng.Next(values.Count)];
...
var rng = new Random();
Console.WriteLine(PickRandomValue(movies, rng).Title);
  • Related