Question Randomized Playlist

AndreasPapandreou

New member
Joined
Jan 13, 2022
Messages
2
Programming Experience
1-3
Hello i am new to c# and trying to create some simple programs and one of those is a randomized playlist for spotify.
When I run the code I get this error:
"Unhandled exception. System.ArgumentOutOfRangeException: Index must be within the bounds of the List. (Parameter 'index')
at System.Collections.Generic.List`1.Insert(Int32 index, T item)
at SpotifyPlaylists.Program.Main() in C:\Users\antre\RiderProjects\SpotifyPlaylists\SpotifyPlaylists\Main.cs:line 21"

the code the following:
C#:
namespace SpotifyPlaylists;
class Program {
    public static void Main(){
      
        List<String> playlist = new List<string>();
        List<String> RandomPlaylist = new List<string>();
        Random rnd = new Random();
      
        Console.WriteLine("Hello at this program we are gonna create you a randomized playlist for your spotify based on your songs.");
        Console.WriteLine("You are gonna text the songs you like one by one. When you don't wanna add any more songs just type DONE");
      
        String song = Console.ReadLine();
      
        while (song.Equals("DONE")==false){
            playlist.Add(song);
            song = Console.ReadLine();
        }

      
        foreach (var i in playlist){
            RandomPlaylist.Insert((rnd.Next((playlist.Count)-1)), i);
        }

        foreach (var i in RandomPlaylist)
        {
            Console.WriteLine(i);
        }
    }
}
 
Last edited by a moderator:
Random.Next(n) will return a number from 0 to n-1, inclusive. If it returns 0 and you subtract 1 like you are currently doing, then you have an index that is out of range.
 
You're trying to insert at an index that is higher than the number of items in RandomPlaylist.
 
@JohnH is right on the money.
 
A higher random number than 0 is statistically more likely, but that could happen too.
Anyway, the approach must be changed. For example if you want to only add the items once you can pick a random index in source, get that item, remove it from source and add it to target list.
 
First of all thank you both for the advices I am starting to see the bigger picture. so I should firstly remove the -1 now for what you said @JohnH could you please be a little more specific?
 
could you please be a little more specific?
Start with this: "pick a random index in source" - can you do that?
pseudo code:
var index = random number from 0 to source list count -1
 
Back
Top Bottom