Question

In: Computer Science

Language: Java A function is said to have side effects if it changes something outside of...

Language: Java

A function is said to have side effects if it changes something outside of its scope or does something other than return a value.

A void function is obviously intended to have side effects; since it doesn't return anything, it is expected to change something. On the other hand, if a function does return something, it is usually expected that it will have no side effects

In this lab, you will complete a method that is intended to have no side effects; you should be able to run this method as many times as you want on an object, with no difference in the result.

Problem Statement
Complete this function so that it returns a count of the number of times an object x of generic type T is found on a Stack.

(In this case, the stack is implemented with linked nodes, but that should be irrelevant to your code; your function should work the same with any implementation of a Stack).

When the method ends the Stack should store exactly the same data as at the beginning of the method. However, your function will need to alter the Stack data as it runs.

Solutions

Expert Solution

Here is the completed code for this method. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks

Note: Since you did not provide the method header (prototype of the method you need), I have created the method entirely from scratch. And below are two different implementations. Choose whichever you prefer. Assuming a stack has basic operations: push(), pop() and isEmpty().

1) Method using loop and a temporary stack to solve this problem.



/**
 * method to count number of times x occur in a given stack, without
 * changing order of elements in stack.
 * 
 * @param <T>
 *            any type
 * @param x
 *            value to be counted
 * @param stack
 *            stack of T type elements
 * @return count of x in stack
 */
public static <T> int count(T x, Stack<T> stack) {
        // initializing count to 0
        int c = 0;
        // creating a temporary stack
        Stack<T> temp = new Stack<T>();
        // looping until stack is empty
        while (!stack.isEmpty()) {
                // removing top value
                T value = stack.pop();
                // if this value equals x, updating count
                if (value.equals(x)) {
                        c++;
                }
                // pushing top value to temp stack
                temp.push(value);
        }
        // now simply moving each element from temp stack to original stack, so
        // that elements will be back in original order.
        while (!temp.isEmpty()) {
                stack.push(temp.pop());
        }
        //returning count
        return c;
}

2) Method using recursion to solve this problem without using another stack.


/**
 * same method, but written recursively, thus avoiding the need to use a
 * secondary stack
 */
public static <T> int count(T x, Stack<T> stack) {
        // base case: if stack is empty, returning 0
        if (stack.isEmpty()) {
                return 0;
        }

        // initializing count to 0
        int c = 0;
        // removing top value
        T value = stack.pop();
        // if this value equals x, updating count
        if (value.equals(x)) {
                c++;
        }
        // finding count of x in remaining stack, recursively, and adding to
        // count
        c += count(x, stack);
        // pushing back removed value.
        stack.push(value);

        // returning count
        return c;
}

Related Solutions

Vaccine have side effects. sometimes those side effects kill. Are vaccine worth the risk?
Vaccine have side effects. sometimes those side effects kill. Are vaccine worth the risk?
using java language only write a code Have the function StringChallenge(str) take the str string parameter...
using java language only write a code Have the function StringChallenge(str) take the str string parameter being passed and return the number of words the string contains (e.g. "Never eat shredded wheat or cake" would return 6). Words will be separated by single spaces. Examples Input: "Hello World" Output: 2 Input: "one 22 three" Output: 3 ------- you have the following code edit it to get the result mport java.util.*; import java.io.*; class Main {   public static String StringChallenge(String str)...
Post an example of something that you have read RECENTLY that is written with persuasive language....
Post an example of something that you have read RECENTLY that is written with persuasive language. Think about places you have been that want to sell things---especially menu items; maybe you have read about someone who wants to earn your trust/ get your vote—there are so many examples of persuasive writing in our everyday lives. Share one here and comment on two other students’ posts.
can anyone summarize this? Robotics and technology have always been something that has been said will...
can anyone summarize this? Robotics and technology have always been something that has been said will “rule the world” someday, and part of that is true! It starts out when they begin taking jobs! One of the most common jobs, in my eyes, that has been taken over by robotics, is proofreading! (Bernazzani, S., N/A) In software like Google Docs and Microsoft Word, we have the ability to tell the computer to proofread our papers, to make sure spelling and...
Suppose a drug is known to have mild side effects in 75% of the people who...
Suppose a drug is known to have mild side effects in 75% of the people who take it . It is administered to 100 people. Using both the binomial distribution and the normal approximation, you have calculated the probability that more than 70 people will experience mild side effects. Based on your answers to the previous questions, choose all that apply. i. Since our experimental conditions satisfy the requirements for its use, the estimate from the normal approximation is appropriate...
Programming language Python It have to be in Functions with a main function Samuel is a...
Programming language Python It have to be in Functions with a main function Samuel is a math teacher at Hogwarts School of Witchcraft and Wizardry. He loves to give his students multiplication exercises. However, he doesn’t care about the actual operation result but the unit sum of its digits. At Hogwarts School of Witchcraft and Wizardry, they define the unit sum (US) of N as the unit that it is left after doing the sum of all the digits of...
JAVA LANGUAGE 1. What is the value of creditScores.length, if you have declared an array as...
JAVA LANGUAGE 1. What is the value of creditScores.length, if you have declared an array as follows: int[] creditScores = {670, 720, 815};? a. 0 b. 1 c. 2 d. 3 2. Which of the following correctly assigns the value 100 to each of the array element? Assume the array is declared as int [] num = new int[4] a. for(x=0;x<3;++x) num[x]=100; c. for(x=1;x<4;++x) num[x]=100 ; 3. Consider the following code fragment int[][] rectangle = new int[4][2]; What is the...
What have you heard about corticosteroid use? What are some of the side effects?
What have you heard about corticosteroid use? What are some of the side effects?
The programming language that is being used here is JAVA, below I have my code that...
The programming language that is being used here is JAVA, below I have my code that is supposed to fulfill the TO-DO's of each segment. This code in particular has not passed 3 specific tests. Below the code, the tests that failed will be written in bold with what was expected and what was outputted. Please correct the mistakes that I seem to be making if you can. Thank you kindly. OverView: For this project, you will develop a game...
Language: Java I have written this code but not all methods are running. First method is...
Language: Java I have written this code but not all methods are running. First method is running fine but when I enter the file path, it is not reading it. Directions The input file must be read into an input array and data validated from the array. Input file format (500 records maximum per file): comma delimited text, should contain 6 fields: any row containing exactly 6 fields is considered to be invalid Purpose of this code is to :...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT