Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Data Structure in Java Working at MusicBest You are planning a road trip and wan

ID: 3752525 • Letter: D

Question

Data Structure in Java

Working at MusicBest

You are planning a road trip and want to create a playlist of your favorite songs. Assume that the song titles are in an array of strings. Create a shuffle of your songs (permutation of your original songs).

Use the Fisher–Yates shuffle algorithm that works in O(n) running time. We will use a method that creates pseudo-random numbers (see end for help) in O(1) running time.

The basic idea is to start from the last element, swap it with a randomly selected element from the whole array (including last). In the next step you will consider the array from 0 to n-2 (size reduced by 1), and repeat the process until you reach the first element.

Write a program that uses the provided Playlist.txt as input and outputs the shuffled array in a file called LastNameFirstNamePlaylist.txt.

Follow the next pseudocode:

To shuffle an array a of n elements (indices 0..n-1):

for i from n - 1 downto 1

j = random integer with 0 <= j <= i

exchange a[j] and a[i]

Create appropriate JUnits to test your program.

Explanation / Answer

Solution:

Please save the LastName.txt, and playlist.txt in the same package/folder where your cod eis saved.

package Chegg;

import java.io.BufferedReader; //package for file handling
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Random; //class for generating random numbers


public class Shuffeling
{
static String[] fisherYatesShuffling(String []arr, int n)
{
String []a = new String[n];
String []ind = new String[n];
for(int i=0; i<n; i++)
ind[i] = "p";
int index;
Random rand = new Random();
for(int i=0; i<n; i++)
{
do
{
index = rand.nextInt(n);
} while(ind[index] != "p");

ind[index] = "q";
a[i] = arr[index];
}
return a;
}

public static void main(String agrs[]) throws Exception
{
String title[]=new String[9];
String shuffle[]=new String[9];
FileWriter fw=null;
BufferedWriter bw=null;
try{
int i=0;
fw=new FileWriter("LastName.txt"); //File name and location in which write the data
bw=new BufferedWriter(fw);
FileReader read=new FileReader("playlist.txt"); // file from the data is reading
BufferedReader rd=new BufferedReader(read);
while(rd.readLine()!=null)
{
title[i]=rd.readLine();
//System.out.println(title[i]);
i++;
  
}
  
rd.close();
read.close();
}catch (Exception ex)
{
System.out.println(ex);
}
//System.out.println("here");
  
shuffle = fisherYatesShuffling(title,9);
  
for(String str:shuffle)
{
try{
  
bw.write(str);
  
}
catch(Exception ex)
{
  
}   
  
System.out.println(str);
}
bw.close();
fw.close();
}
}