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

Need help with creating this method. Don\'t change the method type! Thanks! publ

ID: 3920583 • Letter: N

Question

Need help with creating this method. Don't change the method type!

Thanks!

public static int sharksHuntAndBreed(int[][] fish, int[][] sharks, boolean[][] fishMove,
boolean[][] sharksMove, int sharksBreed, int[][] starve, int sharksStarve, Random randGen) {
//TODO Milestone 2
return 0;
}
  
/**
* This looks up the specified paramName in this Config.SIM_PARAMS array,
* ignoring case. If found then the array index is returned.
* @param paramName The parameter name to look for, ignoring case.
* @return The index of the parameter name if found, otherwise returns -1.
*/
public static int indexForParam(String paramName) {
for ( int i = 0; i < Config.SIM_PARAMS.length; i++) {
if ( paramName.equalsIgnoreCase( Config.SIM_PARAMS[i])) {
return i;
}
}
return -1;
}
  
/**
* Writes the simulationParameters to the file named filename.
* The format of the file is the name of the parameter and value
* on one line separated by =. The order of the lines does not matter.
* Algorithm:
* Open the file named filename for writing. Any IOExceptions should be handled with a throws
* clause and not a try-catch block.
* For each of the simulation parameters whose names are found in Config.SIM_PARAMS
* Write out the name of the parameter, =, the parameter value and then newline.
* Close the file.
*
* Example contents of file:
* seed=233
* ocean_width=20
* ocean_height=10
* starting_fish=100
* starting_sharks=10
* fish_breed=3
* sharks_breed=10
* sharks_starve=4
*  
* @param simulationParameters The values of the parameters to write out.
* @param filename The name of the file to write the parameters to.
*/
public static void saveSimulationParameters(int[] simulationParameters, String filename) throws IOException {

//TODO Milestone 3
}
  
/**
* This loads the simulation parameters from the file named filename.
* The names of the parameters are in the Config.SIM_PARAMS array and the array returned from
* this method is a parallel array containing the parameter values. The name corresponds to
* the value with the same index.
* Algorithm:
* Try to open filename for reading. If the FileNotFoundException is thrown print the
* message printing out the filename without < > and return null;
*
* File not found: <filename>
*
* Read lines from the file as long as each line contains "=". As soon as a line does not
* contain "=" then stop reading from the file. The order of the lines in the
* file is not significant.
* In a line the part before "=" is the name and the part after is the value.
* The separate method you wrote in P7 is helpful here.
* Find the index of the name within Config.SIM_PARAMS (call indexForParam).
* If the index is found then convert the value into an int and store in the corresponding
* index in the array of int that will be returned from this method.
* If the index is not found then print out the message followed by the entire line
* without the < >.
*
* Unrecognized: <line>
*
* @param filename The name of the from which to read simulation parameters.
* @return The array of parameters.
*/
public static int[] loadSimulationParameters(String filename) {
int[] params = null;
//TODO Milestone 3
return params;
}  
  
/**
* This writes the simulation parameters and the chart of the simulation to a file.
* If simulationParameters is null or history is null then print an error message
* and leave the method before any output.
* If filename cannot be written to then this method should throw an IOException. *
*
* Parameters are written first, 1 per line in the file. Use an = to separate the
* name from the value. Then write a blank line and then the Population Chart.
* Example file contents are:
* seed=111
* ocean_width=5
* ocean_height=2
* starting_fish=6
* starting_sharks=2
* fish_breed=3
* sharks_breed=3
* sharks_starve=3
*
* Population Chart
* Numbers of fish(.) and sharks(O) in units of 1.
* F 6,S 2 1)OO....
* F 4,S 2 2)OO..
* F 2,S 4 3)..OO
* F 1,S 4 4).OOO
* F 0,S 4 5)OOOO
*
* Looking at one line in detail
* F 6,S 2 1)OO....
* ^^^^^^ 6 fish (the larger of sharks or fish is in the background)
* ^^ 2 sharks  
* ^^^^^ chronon 1
* ^^^^ the number of sharks
* ^^^^ the number of fish
*
* The unit size is determined by dividing the maximum possible number of a creature
* (oceanWidth * oceanHeight) by Config.POPULATION_CHART_WIDTH.
* Then iterate through the history printing out the number of fish and sharks.
* PrintWriter has a printf method that is helpful for formatting.
* printf("F%3d", 5)
* prints "F 5", a 5 right justified in a field of size 3.
*
* @param simulationParameters The array of simulation parameter values.
* @param history Each element in the ArrayList is an array with information about a specific
* chronon. The array has 3 elements: chronon, number of fish, and number of sharks,
* in that order.
* @param oceanWidth The width of the ocean.
* @param oceanHeight The height of the ocean.
* @param filename The name of the file to write the parameters and chart to.
*/
public static void savePopulationChart(int[]simulationParameters, ArrayList<int[]> history,
int oceanWidth, int oceanHeight, String filename) throws IOException {
//TODO Milestone 3
}
}

Explanation / Answer

public static int sharksHuntAndBreed(int[][] fish, int[][] sharks, boolean[][] fishMove, boolean[][] sharksMove, int sharksBreed, int[][] starve, int sharksStarve, Random randGen) {
        if (fish == null || fish[0].length < 1 || fish.length < 1){ // check for null or less than 1 in each dimension
            System.err.println("sharksHuntAndBreed Invalid fish array: Null or not at least 1 in each dimension.");
            return -1; // return -1 meaning array(s) are bad
        } else if (sharks == null || sharks[0].length < 1 || sharks.length < 1) { // repeat for all arrays in the parameters
            System.err.println("sharksHuntAndBreed Invalid sharks array: Null or not at least 1 in each dimension.");
            return -1;
        } else if (fishMove == null || fishMove[0].length < 1 || fishMove.length < 1) {
            System.err.println("sharksHuntAndBreed Invalid fishMove array: Null or not at least 1 in each dimension.");
            return -1;
        } else if (sharksMove == null || sharksMove[0].length < 1 || sharksMove.length < 1) {
            System.err.println("sharksHuntAndBreed Invalid sharksMove array: Null or not at least 1 in each dimension.");
            return -1;
        } else if (starve == null || starve[0].length < 1 || starve.length < 1) {
            System.err.println("sharksHuntAndBreed Invalid starve array: Null or not at least 1 in each dimension.");
            return -1;
        } else if (sharksBreed < 0) { // if the sharksBreed is negative print an error
            System.err.println("sharksHuntAndBreed sharksBreed value is less than 0");
            return -2;
        } else if (sharksStarve < 0) { // same with sharks starve
            System.err.println("SharksHuntAndBreed sharksStarve value is less than 0");
            return -2;
        } else if (randGen == null) {
            System.err.println("randGen object is null"); // if randGen is null
            return -3; // return -3 meaning randGen is null
        }
      
        // Sharks Hunt and Breed
        for (int i = 0; i < sharksMove.length; i++) { // loop through the entire sharks aray
            for (int j = 0; j < sharksMove[0].length; ++j) {
                if (!sharksMove[i][j] && sharks[i][j] != Config.EMPTY) {
                    if (starve[i][j] >= sharksStarve) { // if the shark starves then call shark starves array
                        sharkStarves(sharks, sharksMove, starve, i, j);
                    } else { //otherwise if it doesnt starve
                        if (fishPositions(fish, i, j).size() == 0) { // if there are not any fish around
                            int[] chosenMove = chooseMove(unoccupiedPositions(fish, sharks, i, j), randGen);
                            if (chosenMove == null) { // if the shark is surrounded by other shakrs
                                sharkStays(sharks, sharksMove, starve, i, j); // the shark stays
                            } else if (sharks[i][j] < sharksBreed) { // if its younger than the breeding age
                                sharkMoves(sharks, sharksMove, starve, i, j, chosenMove[0], chosenMove[1]); // move the shark
                            } else { // otherwise it moves and breds
                                sharkMovesAndBreeds(sharks, sharksMove, starve, i, j, chosenMove[0], chosenMove[1]);
                            }
                        } else { // if there are fish nearby
                            int[] chosenMove = chooseMove(fishPositions(fish, i, j),randGen);
                            if(chosenMove != null && sharks[i][j] < sharksBreed){ // choose a random move and if its not null and the shark is young
                                sharkEatsFish(sharks, sharksMove, starve, fish, fishMove, i, j, chosenMove[0], chosenMove[1]); // shark eats fish
                            } else { // otherwise it eats and breeds
                                sharkEatsFishAndBreeds(sharks, sharksMove, starve, fish, fishMove, i, j, chosenMove[0], chosenMove[1]);
                            }
                        }
                    }
                }
            }
        }
        return 0;
    }

  
   public static void saveSimulationParameters(int[] simulationParameters, String filename) throws IOException {  
       File file = new File(filename);
       FileWriter fw = new FileWriter(file);
       PrintWriter pw = new PrintWriter(fw);
        for (int i = 0; i < simulationParameters.length; i++) { // loop through every sim param
              pw.println(Config.SIM_PARAMS[i] + "=" + simulationParameters[i]); // print the name followed by equal sign and then the param value
          }          
        pw.close();
    }  

public static int[] loadSimulationParameters(String filename) {
        int[] params = null;
        String nextLine = "";
        Scanner sc = null;
        try {
           File file = new File(filename); // make sure this is in a try catch because it doesn't throw an exception automatically
           sc = new Scanner(file);
           params = new int[Config.SIM_PARAMS.length];
           while (sc.hasNextLine()) { // while scanner gets another line
                nextLine = sc.nextLine(); // grab the line
               if (!nextLine.contains("=")) { break; } // if it doesnt contain an "="
               int index = indexForParam(nextLine.substring(0, nextLine.indexOf("="))); // the index is indexForParam of the text before the equal sign
               params[index] = Integer.parseInt(nextLine.substring(nextLine.indexOf("=")+1)); // the number is everything after the
           }
        } catch (FileNotFoundException e) {
           System.err.println("File not found: " + filename); // catch the exception if file DNE
        } catch (Exception e) {
           System.err.println("Unrecognized: " + nextLine); // catch if one of the lines is unrecognized
        } finally {
           if (sc != null) { sc.close(); }
        }
        return params;
    }

  
  
public static void savePopulationChart(int[]simulationParameters, ArrayList<int[]> history, int oceanWidth, int oceanHeight, String filename) throws IOException {
        //save all the parameters
        File file = new File(filename);
        FileWriter fw = new FileWriter(file);
        PrintWriter pw = new PrintWriter(fw);
        for (int i = 0; i < simulationParameters.length; i++) {
            pw.println(Config.SIM_PARAMS[i] + "=" + simulationParameters[i]); // do the same method as saveSimulationParameters
        }         
        pw.print(" Population Chart Numbers of fish(" + Config.FISH_MARK + ") and sharks(" + Config.SHARK_MARK +") in units of " + (oceanWidth * oceanHeight) / Config.POPULATION_CHART_WIDTH + ".");
        pw.println();
        for (int i = 0; i<history.size(); i++) {   // loop through the size of history (how many chronons there are)
            int unitSize = getCeil((oceanWidth * oceanHeight), Config.POPULATION_CHART_WIDTH); // round unit size to ceiling
            int sharkMarks = getCeil(history.get(i)[Config.HISTORY_NUM_SHARKS_INDEX], unitSize); // get how many shark chars and fish you will need to print
            int fishMarks = getCeil(history.get(i)[Config.HISTORY_NUM_FISH_INDEX], unitSize);
            String sharksAndFishLine = ((history.get(i)[Config.HISTORY_NUM_SHARKS_INDEX]) > (history.get(i)[Config.HISTORY_NUM_FISH_INDEX])) // uses a ternary operator to see if sharks are greater or if fish are
                                ? new String(new char[fishMarks]).replace('', Config.FISH_MARK) // if the sharks are more create a char array of fish characters that are fish units long then add the remaining sharks to the end
                                    + new String(new char[sharkMarks - fishMarks]).replace('', Config.SHARK_MARK) // if there are more fish than sharks create a char array of sharks units long then add the remaining fish to the end
                                : new String(new char[sharkMarks]).replace('', Config.SHARK_MARK)
                                    + new String(new char[fishMarks - sharkMarks]).replace('', Config.FISH_MARK);
            sharksAndFishLine += new String(new char[Config.POPULATION_CHART_WIDTH - sharksAndFishLine.length()]).replace('', ' '); // add remaining white space to the end
            pw.printf("F%3d,S%3d%5d)%s", history.get(i)[Config.HISTORY_NUM_FISH_INDEX], history.get(i)[Config.HISTORY_NUM_SHARKS_INDEX], history.get(i)[Config.HISTORY_CHRONON_INDEX], sharksAndFishLine);
            pw.println(); // ^^ print f with all of them combined cause i just wanted to do it in one line
        }
        pw.close();
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote