Rearrange the shuffled trip plan



Rearrange the shuffled sticky notes(trip plan-each note consists of starting place and place for night stay for that particular day)
Sample Input:
Vellore Bangalore
Mysore Goa
Bangalore Mysore
Chennai Vellore


Sample output:
Chennai Vellore
Vellore Bangalore
Bangalore Mysore
Mysore Goa
 

Steps:
  • First we have to find the starting pair. Chennai is the starting place because no pair ends with chennai. We will find that in the first step.
  • Having the first pair as Chennai to vellore, we can find the next pair by checking pair containing vellore as starting place. So next we have vellore, Bangalore. Similarly we search for bangalore and then for mysore.

Code:

public class Program2 {
   
    public static void main(String[] args){
       
        String[][] places = {{"Vellore","Bangalore"},{"Mysore", "Goa"},{"Bangalore","Mysore"},{"Chennai","Vellore"}};
       
        int numplaces = places.length;
       
        String[] temp = places[0];
        String[][] result = new String[numplaces][2];
       
        for(int i=0; i<numplaces; i++){
            boolean present = false;
            for(int j=0; j<numplaces; j++){
                if(places[i][0].equals(places[j][1])){
                    present = true;
                    break;
                }
               
            }
            if(!present){
                temp = places[i];
                break;
            }
        }
       
        result[0] =temp;
       
        int count = 0;
       
        for(int i=0; i<numplaces; i++){
       
            for(int j=0; j<numplaces; j++){
               
                if(result[i][1].equals(places[j][0])){
                    result[++count] = places[j];
                   
                }
               
            }
        }
       
        for(int i=0; i<numplaces; i++){
           
            for(int j=0; j<2; j++){
               
                System.out.print(result[i][j]+" ");
            }
           
            System.out.println();
        }
       
    }

}


Output:
Chennai Vellore
Vellore Bangalore
Bangalore Mysore
Mysore Goa


Comments

Popular posts from this blog

Rearrange Array in Maximum-Minimum form

Second Largest Element

Check if a number is a power of another number