Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement a function to return true if array or arrayList refers to a previous element?

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();
    }
}
like image 465
RShome Avatar asked Apr 23 '19 11:04

RShome


1 Answers

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;
}
like image 90
Conffusion Avatar answered Oct 21 '22 06:10

Conffusion