Question

In: Computer Science

In this problem, we provide you with a Java file called Question2.java. Suppose that there is...

In this problem, we provide you with a Java file called Question2.java. Suppose that there is an array and let us call this array, items. The array items contains n integers. These n integers are in a completely random order in the array. What you are asked to do is to reorder the items in the array such that all the negative integers come before all the zeros and all the positive integers appear at the end. Note, this question is not asking you to sort the numbers in the array. It is asking you to reorder them

In this first example, you can see that the array initially contains the integers 7, −3, 0, 0, 8 and −2. Now, this is in some random order. What you must do to this array, is to reorder the numbers such that the array has three distinct pieces (also called constraints) represented by < 0, == 0 and > 0. You can see that in the first region, we place all the numbers that are less than 0, followed by all zeros and then followed by any numbers that are greater than 0. The numbers within each region can be in any order, as long as they happen to fulfill the constraint.

2. You can only visit all the numbers in the array once. i.e., you are not allowed to have nested loops. Neither can you create a new array or use an array list. You should be able to work on this problem simply by visiting every number once. You must mutate the array that is already provided to you and make changes to this array itself.

3. Do not sort any numbers. If you were to sort the numbers, you would receive zero for this question.

4. The numbers within each region can be in any order, as long as they happen to fulfill the constraint.

5. You cannot assume that there will be at least a single zero in the array. You may very well have an array with all zeros or an array that contains no zero. Assuming that the array contains only negative numbers and positive numbers (≥ 1) If this is the case, you will proceed with reordering the items in the array such that you have negative numbers followed by positive numbers. 6. We provide to you the following methods that must be completed

starter code:

package 3;
//Make sure to copy/paste the honor code and fill in all the required details. 
//If you do not complete the honor code, your assignment will not get marked.
import java.util.Arrays;

public class Question2 {
        /*
         * TODO: You are asked to complete the method
         * rearranging. This method takes in as input an 
         * array of ints and returns back nothing (void).
         * You cannot change the function 
         * signature of this method. Your method question2 must call
         * the swap method. Scroll down to find the swap method.   
         * You cannot use any kind of sorting to answer this question. 
         */
        public static void question2(int[] items)
        {
                
        }
        
        /*
         * TODO: You are asked to complete the method
         * swap. This method takes in as input two ints
         * and an array of ints. The int i and int j 
         * are the index i and index j in the array items.
         * You are asked to swap the value at the index i in items
         * with the value at the index j. You cannot change the function 
         * signature of this method. This method must be called inside question2. 
         */
        private static void swap(int i,int j,int[] items)
        {
                
                
        }

        
        /*
         * Do not write any code inside the main method and expect it to get marked. 
         * Any code that you write inside the main method will be ignored. However, 
         * you are free to edit the main function in any way you like for 
         * your own testing purposes. 
         */
        public static void main(String[] args) {
                
                
                int [] items={-7,-3,20,10,8,2};
                Question2.question2(items);
                System.out.println(Arrays.toString(items)); //must print [-7, -3, 10, 8, 2, 20]
                
                int [] items1={1,1,1,1,1,1,1,1};
                Question2.question2(items1);
                System.out.println(Arrays.toString(items1)); //must print [1, 1, 1, 1, 1, 1, 1, 1]
                
                
                int [] items2={1,2,3,4,5,6,7,8,9};
                Question2.question2(items2);
                System.out.println(Arrays.toString(items2)); //must print [2, 3, 4, 5, 6, 7, 8, 9, 1]
                
                int [] items3={6,7,8,0,1,2,3,-1,-2};
                Question2.question2(items3);
                System.out.println(Arrays.toString(items3)); //must print [-2, -1, 0, 1, 2, 3, 8, 7, 6]
                
                
                
                int [] items4={0,0,0,0,1,2,3,-1,-2,-3};
                Question2.question2(items4);
                System.out.println(Arrays.toString(items4)); //must print [-3, -2, -1, 0, 0, 0, 0, 3, 2, 1]
                
                int [] items5={-1,4,5,6,0,0,0,-2};
                Question2.question2(items5);
                System.out.println(Arrays.toString(items5)); //must print [-1, -2, 0, 0, 0, 6, 5, 4]
                
                
        }
}

Solutions

Expert Solution

The below code satisfies all the constraints described in the problem statement. The outputs may not match with the comments mentioned in main method but the output given by this below program satisfies all the constraints.

import java.util.Arrays;

public class Question2 {
    /*
     * rearranging. This method takes in as input an
     * array of ints and returns back nothing (void).
     * You cannot change the function
     * signature of this method. Your method question2 must call
     * the swap method. Scroll down to find the swap method.
     * You cannot use any kind of sorting to answer this question.
     */
    public static void question2(int[] items)
    {
        if( items.length > 1){
            int j = 0; // keeps track of the index of last parsed number which is less than or equals to zero
            int countZeroes = 0; // keeps track of number of zeroes in order to get the index of last parsed negative number

            for(int i=0; i<items.length; i++){
                if(items[i] < 0){
                    if(i!=j)
                        swap(i, j, items);
                    // swaps the first 0 with the negative number if 0s exist
                    if(countZeroes>0)
                        swap(j-countZeroes, j, items);
                    j++;
                }
                else if( items[i] == 0 ){
                    if(i!=j)
                        swap(i, j, items);
                    j++;
                    countZeroes++;
                }
            }
        }
    }

    /*
     * swap. This method takes in as input two ints
     * and an array of ints. The int i and int j
     * are the index i and index j in the array items.
     * You are asked to swap the value at the index i in items
     * with the value at the index j. You cannot change the function
     * signature of this method. This method must be called inside question2.
     */
    private static void swap(int i,int j,int[] items)
    {
        // The below code swaps the elements without using any extra variable
        items[i] = items[i] + items[j];
        items[j] = items[i] - items[j];
        items[i] = items[i] - items[j];
    }


    /*
     * Do not write any code inside the main method and expect it to get marked.
     * Any code that you write inside the main method will be ignored. However,
     * you are free to edit the main function in any way you like for
     * your own testing purposes.
     */
    public static void main(String[] args) {


        int [] items={-7,-3,20,10,8,2};
        Question2.question2(items);
        System.out.println(Arrays.toString(items)); //must print [-7, -3, 10, 8, 2, 20]

        int [] items1={1,1,1,1,1,1,1,1};
        Question2.question2(items1);
        System.out.println(Arrays.toString(items1)); //must print [1, 1, 1, 1, 1, 1, 1, 1]


        int [] items2={1,2,3,4,5,6,7,8,9};
        Question2.question2(items2);
        System.out.println(Arrays.toString(items2)); //must print [2, 3, 4, 5, 6, 7, 8, 9, 1]

        int [] items3={6,7,8,0,1,2,3,-1,-2};
        Question2.question2(items3);
        System.out.println(Arrays.toString(items3)); //must print [-2, -1, 0, 1, 2, 3, 8, 7, 6]



        int [] items4={0,0,0,0,1,2,3,-1,-2,-3};
        Question2.question2(items4);
        System.out.println(Arrays.toString(items4)); //must print [-3, -2, -1, 0, 0, 0, 0, 3, 2, 1]

        int [] items5={-1,4,5,6,0,0,0,-2};
        Question2.question2(items5);
        System.out.println(Arrays.toString(items5)); //must print [-1, -2, 0, 0, 0, 6, 5, 4]


    }
}

Output is as follows:


Related Solutions

Python programming problem! Suppose that there is a json file called data from the desktop. I...
Python programming problem! Suppose that there is a json file called data from the desktop. I want to print the value with the key of "year" and "country". Json file below: { "A":{ "year":11, "grade":A, "country":America}, "B":{ "year":18, "grade":C, "country":England}, "C":{ "year":19, "grade":B, "country":China},} I want a code that I can only replace the name of key from year to grade and the code could be work.
Write a Java class called CityDistances in a class file called CityDistances.java.    1. Your methods...
Write a Java class called CityDistances in a class file called CityDistances.java.    1. Your methods will make use of two text files. a. The first text file contains the names of cities. However, the first line of the file is a number specifying how many city names are contained within the file. For example, 5 Dallas Houston Austin Nacogdoches El Paso b. The second text file contains the distances between the cities in the file described above. This file...
Write a public Java method called WriteToFile that opens a file called words.dat which is empty....
Write a public Java method called WriteToFile that opens a file called words.dat which is empty. Your program should read a String array called words and write each word onto a new line in the file. Your method should include an appropriate throws clause and should be defined within a class called TextFileEditor. The string should contain the following words: {“the”, “quick”, “brown”, “fox”}
Write a java program that will read a file called stateinfo.txt and will store the information...
Write a java program that will read a file called stateinfo.txt and will store the information of the file into a map. The stateinfo.txt file contains the names of some states and their capitals. The format of stateinfo.txt file is as follows. State                Capital ---------                         ----------- NSW               Sydney VIC                 Melbourne WA                 Perth TAS                 Tasmania QLD                Brisbane SA                   Adelaide The program then prompts the user to enter the name of a state. Upon receiving the user input, the program should...
1. Write a public Java class called WriteFile which opens an empty file called letters.dat. This...
1. Write a public Java class called WriteFile which opens an empty file called letters.dat. This program will read a String array called letters and write each word onto a new line in the file. The method should include an appropriate throws clause and should be defined within a class called TFEditor. The string should contain the following words: {“how”, “now”, “brown”, “cow”}
Using JAVA The following code is able to read integers from a file that is called...
Using JAVA The following code is able to read integers from a file that is called "start.ppm" onto a 3d array called "startImage". Implement the code by being able to read from another file (make up any file name) and save the data onto another 3d array lets say you call that array "finalImage". The purpose of this will be to add both arrays and then get the average Save the average onto a separte 3darray,lets say you call it...
Write a program called Assignment3 (saved in a file Assignment3 .java) that asks a user to...
Write a program called Assignment3 (saved in a file Assignment3 .java) that asks a user to enter two strings. First, the program prompts: Please enter a string. The program should read in the string, and prompts: Please enter another string. The program reads in two strings and it prints a menu to the user. The program asks for user to enter an option and performs one of the following: Here are the options on the menu: Option a: checks if...
In java Write a program called FileProcessor.java that reads the file numbers.txt, and: Calculate the total...
In java Write a program called FileProcessor.java that reads the file numbers.txt, and: Calculate the total number of numbers in the file, Calculate the sum of all the numbers in the file, Calculate the average of all the numbers in the file, Find the smallest value of all the numbers in the file, Find the largest value of all the numbers in the file, Calculate the standard deviation of all the numbers in the file
Using JAVA The following code is able to read integers from a file that is called...
Using JAVA The following code is able to read integers from a file that is called "start.ppm" onto a 3d array called "startImage". Implement the code by being able to read from another file (make up any file name) and save the data onto another 3d array lets say you call that array "finalImage". The purpose of this will be to add both arrays and then get the average Save the average onto a separte 3darray,lets say you call it...
Suppose we have a Java class called Person.java public class Person { private String name; private...
Suppose we have a Java class called Person.java public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName(){return name;} public int getAge(){return age;} } (a) In the following main method which lines contain reflection calls? import java.lang.reflect.Field; public class TestPerson { public static void main(String args[]) throws Exception { Person person = new Person("Peter", 20); Field field = person.getClass().getDeclaredField("name"); field.setAccessible(true); field.set(person, "Paul"); } }...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT