Question

In: Computer Science

A. Working at Music Best You are planning a road trip and want to create a...

A. Working at Music Best

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 by1), 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=n-1 down to 1 j= random integer with 0 <= j < i

exchange a[j] and a[i]

Count the time to read from the file, to shuffle the songs and to create the output. Note: To count the time use system.currentTimeMillis().

Create appropriate JUnits to test your program. Help with JUnits:

Instructions for developing JUnit:

• To compare two text files in Junit, you can try the following code. Use BufferedReader to read the input files.

BufferedReader Out=new BufferedReader (new FileReader (<Path of output file>));

BufferedReader In=new BufferedReader (new FileReader (<Path of input file>));

while ((expectedLine = In.readLine ()) != null) {

String actualLine = Out.readLine ();

assertEquals (expectedLine, actualLine);

}

• Set seed value as 20.

Random r=new Random();

r.setSeed(20);

Compare the output file with attached see next:

if you use nextDouble() use Target1.txt to compare

double d = random.nextDouble();

int j = (int)(d*arr.length);

else if you use nextInt() use Target2.txt

Programming Standards:

• Your header comment must describe what your program does.

• You must include a comment explaining the purpose of every variable or named constant you use in your program.

• You must use meaningful identifier names that suggest the meaning or purpose of the constant, variable, function, etc.

• Precede every major block of your code with a comment explaining its purpose. You don't have to describe how it works unless you do something tricky.

• You must use indentation and blank lines to make control structures more readable.

Deliverables:

Your main grade will be based on (a) how well your tests cover your own code, (b) how well your code does on your tests (create for all non-trivial methods), and (c) how well your code does on my tests (which you have to add to your test file). For JUnit tests check canvas.

Use cs146S19.<lastname>.project1 as your package, and Test classes should be your main java file, along with your JUnit java tests.

Do not use any fancy libraries. We should be able to compile it under standard installs. Include a readme file on how to compile the project.

***********************************************************************************************************************************************************************************************************

MY SOLUTION:

package RandomMusic;

import static org.junit.Assert.*;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Random;

*playMusicTest.java


public class playMusicTest {

@Test
public void playMusictest() throws IOException
{
  
File file = new File("src\\RandomMusic\\Playlist.txt");
File file1 = new File("src\\RandomMusic\\Target1.txt");
// read input playlist
BufferedReader in = new BufferedReader(new FileReader(file));
// read output target
BufferedReader out = new BufferedReader(new FileReader(file1));
  
String[] playList = new String[459]; // create an array
int i=0; // element of array
String str;
  
// read content of Playlist.txt then copy the content to array
while((str = in.readLine())!=null)
{
playList[i] = str;
i++;
}
  
// random number
Random rand = new Random(0);
rand.setSeed(20);
  
// swap the chosing song.
for(int j = playList.length - 1;j>0;j--)
{
int index = rand.nextInt(j);
String tmp;
tmp = playList[index];
playList[index] = playList[j];
playList[j]= tmp;
}
  
// compare output of playlist = content of target file
for(int k=0; k<playList.length;k++)
{
String actualLine = out.readLine();
assertEquals(playList[k],actualLine);
  
}
  
}

}

*RandomMusic.java

package RandomMusic;

import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Random;
import java.io.*;


public class RandomMusic {
  
String[] playList = new String[459]; // String of playList
int i = 0;
Random rand; // random
BufferedReader in; // read file
  
  
// Open a Text File
public void openFile() throws IOException
{
try {
File file = new File("src\\RandomMusic\\Playlist.txt");
in = new BufferedReader(new FileReader(file));
String str;
while((str = in.readLine())!=null)
{
playList[i] = str;
i++;
}
  
} catch(Exception e) {
System.out.println("Could not find the data file!");
}
  
}
  
// close File
public void closeFile() throws IOException
{
in.close();
  
}

// Swap song in playlist
public void swap(int index, int j)
{
String tmp;
tmp = playList[index];
playList[index] = playList[j];
playList[j]= tmp;
}
  
// Random song in playlist then swap if the song chose
public void playMusic()
{
rand = new Random();
for(int j = playList.length - 1;j>0;j--)
{
int index = rand.nextInt(j);
swap(index,j);
}
}
  
// print out playlist
public void printOut()
{
for(int j=0; j<playList.length;j++)
{
System.out.println(playList[j]);
}
}
  
// Main program
public static void main(String[] args) throws IOException
{
RandomMusic favorMusic = new RandomMusic(); // create RandomMusic
favorMusic.openFile(); // read file
favorMusic.playMusic(); // random music
favorMusic.printOut(); // print out playlist
favorMusic.closeFile(); // close file
}

}

*openFileTest

package RandomMusic;

import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;

import org.junit.Test;

// Check playlist file is exists
public class openFileTest {

@Test
public void openFiletest() throws IOException
{
File file = new File("src\\RandomMusic\\Playlist.txt");
assertTrue(file.exists());
}

  
}

************************************************

I am getting error in playMusicTest.java.... Please help.

Solutions

Expert Solution

I have changed the playMusicTest.java as below

package RandomMusic;

import static org.junit.Assert.*;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;

public class playMusicTest {

   @Test
   public void playMusictest() throws IOException {
       //File file = new File("src\RandomMusic\Playlist.txt");
       File file1 = new File(playMusicTest.class.getClassLoader()
               .getResource("RandomMusic/Target1.txt").getFile());

       // read input playlist
       BufferedReader in = new BufferedReader(new InputStreamReader(
               playMusicTest.class.getClassLoader()
               .getResourceAsStream("RandomMusic/Playlist.txt")));

       // read output target
       BufferedReader out = new BufferedReader(new FileReader(file1));

       String[] playList = new String[459]; // create an array
       int i = 0; // element of array
       String str;

       // read content of Playlist.txt then copy the content to array
       while ((str = in.readLine()) != null) {
           playList[i] = str;
           i++;
       }

// random number
       Random rand = new Random(0);
       rand.setSeed(20);

// swap the chosing song.
       for (int j = playList.length - 1; j > 0; j--) {
           int index = rand.nextInt(j);
           String tmp;
           tmp = playList[index];
           playList[index] = playList[j];
           playList[j] = tmp;
       }

// compare output of playlist = content of target file
       for (int k = 0; k < playList.length; k++) {
           String actualLine = out.readLine();
           assertEquals(playList[k], actualLine);

       }

   }

}

output

And it succeed.


Related Solutions

Paul and Susan are planning a trip to Greece and they want to save for this...
Paul and Susan are planning a trip to Greece and they want to save for this trip. They will need RM12,000 for each person at the end of four years. Both of them can invest a certain amount together at the beginning of each of the next four years in a bank account that will pay 6.8 percent annually. Required: Calculate the total amount they need and how much they will have to invest annually to reach their target?
You are planning a May camping trip to Denali National Park in Alaska and want to...
You are planning a May camping trip to Denali National Park in Alaska and want to make sure your sleeping bag is warm enough. The average low temperature in the park for May follows a normal distribution with a mean of 32°F and a standard deviation of 8°F. 1. What is the probability that the low temperature on a given night will be between 22°F and 29°F? Include 4 decimal places in your answer. 2. What temperature must the sleeping...
2. You are planning a trip to Europe and Japan and want to change U.S. dollars...
2. You are planning a trip to Europe and Japan and want to change U.S. dollars into euros and yen. Your bank provides the following quotes: Currency Bid Ask Euros $1.194 $1.245 Yen $0.009245 $0.00967 (a) What are the bank's relative bid/ask spreads for the two currencies? (b) How much would you lose if you converted $500 into euros and $500 into yen respectively, and then back into dollars? (c) If you need to convert €1,000 Euros into Japanese Yen,...
Thinking of a trip that you or someone you know, is planning on taking. In planning...
Thinking of a trip that you or someone you know, is planning on taking. In planning a budget for the trip, what types of costs should be included in the budget? List at least five costs. Classify the costs as either fixed or variable, explaining what the variable cost drivers are.
You are planning to take a spring break trip to Canada your senior year. The trip...
You are planning to take a spring break trip to Canada your senior year. The trip is exactly two years away, but you want to be prepared and have enough money when the time comes. Explain how you would determine the amount of money you will have to save in order to pay for the trip. 2. Identify the steps involved in computing the present value when you have multiple cash flows.
Create a view named ReservationCustomer_VW. It consists of the reservation ID, trip ID, trip name, trip...
Create a view named ReservationCustomer_VW. It consists of the reservation ID, trip ID, trip name, trip date, customer number, customer last name, customer first name, and phone number for trips whose guide is Glory Unser or Susan Kiley. Show the SQL Server code for this view.
You are planning on flying out of an airport on a trip. The airport parking garage...
You are planning on flying out of an airport on a trip. The airport parking garage charges $6 per day for the first four days, $4 per day for the next three days and $2 per day thereafter. A parking garage just outside the airport charges $5 per day and provides a free shuttle to the airport. When is it more cost-effective to park at the airport parking garage? Your solution MUST include responses to ALL four parts. a) Understand...
You are planning a trip to go see relatives for the Holiday Break. You know your...
You are planning a trip to go see relatives for the Holiday Break. You know your relatives live in a city which is 250 km away. If you can average a speed of 60 mile per hour, how long will you need to plan to get there? a) 15000 minutes b) 4.2 hr c) 9300 sec d) 160 minutes
You want to take out a personal loan to finance a trip to Europe. You estimate...
You want to take out a personal loan to finance a trip to Europe. You estimate that you will need $7500 and the bank offers you a 4-year term at 1.98%, compounded quarterly.What will your payments be each month?
q27. a) you are planning to buy a new caravan to make a trip around australia....
q27. a) you are planning to buy a new caravan to make a trip around australia. the cost of the van is $225000 and you can get a loan from the bank for that amount. if you can get a fifteen year loan at 8.75% per annum compounded fortnightly, how much do you need to pay every fortnight? b) suppose you are going to receive $2000 per year for five years. the appropriate interest is 6% per annum. what is...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT