A playlist is considered a repeating playlist if any of the songs contain a reference to a previous song in the playlist. Otherwise, the playlist will end with the last song which points to null.
I need to Implement a function isRepeatingPlaylist that, returns true if a playlist is repeating or false if it is not.
For example, the following code prints "true" as both songs point to each other.
Song first = new Song("Hello");
Song second = new Song("Eye of the tiger");
first.setNextSong(second);
second.setNextSong(first);
System.out.println(first.isRepeatingPlaylist());
Again, this is not a homework exercise, I am doing coding challenges because when I read theory about programming concepts, I can almost understand, but when faced with writing a program I don't know where to start, or how to apply.
public class Song {
private String name;
private Song nextSong;
public Song(String name) {
this.name = name;
}
public void setNextSong(Song nextSong) {
this.nextSong = nextSong;
}
public boolean isRepeatingPlaylist() {
//throw new UnsupportedOperationException("Waiting to be implemented.");
List<String> list = new ArrayList<String>();
list.add(one);
list.add(two);
list.add(three);
list.add(four);
if list.contains()
return true;
else
return false;
}
public static void main(String[] args) {
Song first = new Song("Hello");
Song second = new Song("Eye of the tiger");
Song third = new Song("a test");
Song fourth = new Song("survivor");
first.setNextSong(second);
second.setNextSong(first);
System.out.println(first.isRepeatingPlaylist();
}
}
You can loop through the playlist and add every song to a set on condition it is not yet in the set. Once you reach the end of the list your list is not a repeating list. If you find a song which exists already in the set, you have a repeating list.
public boolean isRepeatingList(Song firstSong)
{
Set<Song> uniqueSongs=new HashSet<>();
uniqueSongs.add(firstSong);
Song current=firstSong;
while(current.getNextSong()!=null)
{
if(uniqueSongs.contains(current.getNextSong()))
return true;
// add the song to the set, and assign current to the next song
uniqueSongs.add(current=current.getNextSong());
}
// we reached the end of the list without finding any doubles, so:
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With