Question

The game starts when I give you some Teddy bears. You can then give back some bears, but you must follow these rules (where n is the number of bears that you have):

  1. If n is even, then you *may* give back exactly n/2 bears.
  2. If n is divisible by 3 or 4, then you *may* multiply the last two digits of n and give back this many bears. (By the way, the last digit of n is n%10, and the next-to-last digit is ((n%100)/10).
  3. If n is divisible by 5, then you *may* give back exactly 42 bears.

The goal of the game is to end up with EXACTLY 42 bears.

For example, suppose that you start with 250 bears. Then you could make these moves:

  • --Start with 250 bears.
  • --Since 250 is divisible by 5, you may return 42 of the bears, leaving you with 208 bears.
  • --Since 208 is even, you may return half of the bears, leaving you with 104 bears.
  • --Since 104 is even, you may return half of the bears, leaving you with 52 bears.
  • --Since 52 is divisible by 4, you may multiply the last two digits (resulting in 10) and return these 10 bears. This leaves you with 42 bears.
  • --You have reached the goal!

For each integer 50, 51, 52, ..., 500, tell me if 42 can be reached and if so, what are the steps. Notice I use a stack to reverse the print out, so it is more readable. For example, the output of the last few cases are shown here:

Starting number: 496 n=496, return 248. Now n=248. n=248, return 32. Now n=216. n=216, return 6. Now n=210. n=210, return 42.

import java.util.*;

public class Hw18_1 {

public static void main(String[] args) {

Stack<String> stack = new Stack<>();

for (int i = 50; i <= 500; i++) {

System.out.println("\nStarting number:" + i);

if (bears(stack, i))

while (!stack.isEmpty())

System.out.println(stack.pop());

else

System.out.println("No solution");

}

}

static boolean bears(Stack<String> stack, int n) {

int product;

if (n == 42) {

return true;

} else if (n < 42) {

// your work

} else if ((n % 2 == 0) && bears(stack, n / 2)) {

// your work

} else if ((n % 5 == 0) && bears(stack, n - 42)) {

// your work

} else {

product = ((n % 100) / 10) * (n % 10);

// your work

}

return false;

}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Code:

import java.util.*;

public class Hw18_1 {
public static void main(String[] args) {
// stack to store the values that are returned each time
Stack<String> stack = new Stack<>();
// for each value of i call the bears function and print output
for (int i = 50; i <= 500; i++) {
System.out.println("\nStarting number:" + i);
int curr=i;
// if bears function returned true then print solution
if (bears(stack, i))
while (!stack.isEmpty()){
String val=stack.pop();
int value=Integer.parseInt(val);
System.out.println("n="+curr+", return "+value+". Now n="+(curr-value)+".");
curr-=value;
}
// else there is no solution
else
System.out.println("No solution");
}
}
static boolean bears(Stack<String> stack, int n) {
int product;
// base case if n==42 then return true
if (n == 42) {
return true;
}
// if n<42 then it is never possible
if (n < 42) {
return false;
}
// if divisible by 2 , then return n/2
if ((n % 2 == 0) && bears(stack, n / 2)) {
stack.push(Integer.toString(n/2));
return true;
}
// divisible by 5 ,then return 42
if ((n % 5 == 0) && bears(stack, n - 42)) {
stack.push(Integer.toString(42));
return true;
}
// if divisible by 3 or 4 , return product of last 2 digit
if((n % 3 == 0) || (n % 4 == 0)){
product = ((n % 100) / 10) * (n % 10);
// if product is 0 then we need to return othewise
// the function would get stuck in infinite loop
if(product==0) return false;
if(bears(stack,n-product)){
stack.push(Integer.toString(product));
return true;
}
}
// no soultion possible so return false
return false;
}
}

============

Note:

I have modified the given template as the function bears template wasn't correct. Further to match the given sample output I have modified the main too.

============

Sample output along with code screenshot :

1 import java.util.*; n=168, return 84. Now n=84. n=84, return 42. Now n=42. Starting number:491 No solution 3- public classreturn true; // if n<42 then it is never possible if (n < 42) { return false; Starting number: 496 n=496, return 248. Now n=2

============

Explanation:

In bears function since there was no hard bound rule that if number is divisible by 2 then we return n/2. Note that it was one of the possiblities to get the solution.

So instead of stating conditions in if -elseif -else pattern only if conditions are used. And once the solution is found we return from the function immediately.

Here see line 49 => Let's say n = 108 then product would be 0, so again call for 108 and so on.. That's why this condition is required.

Comments have been added for your understanding.

===========

Please upvote

For any doubts comment.

Add a comment
Know the answer?
Add Answer to:
The game starts when I give you some Teddy bears. You can then give back some...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • *JAVA* Can somebody take a look at my current challenge? I need to throw a different...

    *JAVA* Can somebody take a look at my current challenge? I need to throw a different exception when a)(b is entered. It should throw "Correct number of parenthesis but incorrect syntax" The code is as follows. Stack class: public class ArrayStack<E> {    private int top, size;    private E arrS[];    private static final int MAX_STACK_SIZE = 10;    public ArrayStack() {        this.arrS = (E[]) new Object[MAX_STACK_SIZE];        this.top = size;        this.size = 0;...

  • JAVA LANG PLEASE: I have follwed these below guidelines but when i run my queue test...

    JAVA LANG PLEASE: I have follwed these below guidelines but when i run my queue test it is not executing but my stack is working fine, can you fix it please! MyQueue.java Implement a queue using the MyStack.java implementation as your data structure.  In other words, your instance variable to hold the queue items will be a MyStack class. enqueue(String item): inserts item into the queue dequeue(): returns and deletes the first element in the queue isEmpty(): returns true or false...

  • This is the code I have written for a BingoBall program, I'd appreciate it if someone...

    This is the code I have written for a BingoBall program, I'd appreciate it if someone could help me fix this public class BingoBall { private char letter; private int number; // NOTE TO STUDENT // We challenge you to use this constant array as a lookup table to convert a number // value to its appropriate letter. // HINT: It can be done with with a single expression that converts the number // to an index position in the...

  • Having trouble with the do while/while loop and the switch statement. I got some of the...

    Having trouble with the do while/while loop and the switch statement. I got some of the switch statement but cant get the program to repeat itself like it should.What i have so far for my code is below. Any help is appreciated... i am not sure what I am doing wrong or what i am missing. I am completely lost on the while loop and where and how to use it in this scenario. import java.util.Scanner; public class sampleforchegg {...

  • I have spent so much time on this and I am having trouble getting all the...

    I have spent so much time on this and I am having trouble getting all the methods to work together correctly to run the code right, and I am not sure what is wrong with it. /* You will recreate one or two versions of the logic game shown in the Algorithms movie and you will ask which one the user would like to play. Upon completion of the game, display who won and ask if they would like to...

  • how would I complete this code without calling any built-in java collection framework classes like ArrayList,...

    how would I complete this code without calling any built-in java collection framework classes like ArrayList, LinkedList, etc? import java.util.Iterator; class CallStack<T> implements Iterable<T> { // You'll want some instance variables here public CallStack() { //setup what you need } public void push(T item) { //push an item onto the stack //you may assume the item is not null //O(1) } public T pop() { //pop an item off the stack //if there are no items on the stack, return...

  • Need help with this binary tree program. I will give a thumbs up for anybody who...

    Need help with this binary tree program. I will give a thumbs up for anybody who helps. Source Code: import java.util.Random; import java.util.Scanner; import java.util.Arrays; import java.util.Collections; import java.util.ArrayList; public class Trees { public static int[] prepareData(int[] data){ /* Data is prepared by inserting random values between 1 and data.length. Data items may be assumed to be unique. Please refer to lab spec for the problem definiton. */ ArrayList list = new ArrayList(); for (int i=0; i< data.length; i++) {...

  • Can you help me rearrange my code by incorporating switch I'm not really sure how to...

    Can you help me rearrange my code by incorporating switch I'm not really sure how to do it and it makes the code look cleaner. Can you help me do it but still give the same output? Also kindly add an in-line comment on what changes and rearrangement you've done so I can understand what's going on. import java.util.ArrayList; import java.util.Scanner; public class Bank { /** * Add and read bank information to the user. * @param arg A string,...

  • help finish Queue, don't think I have the right thing. # 1. After studying the Stack...

    help finish Queue, don't think I have the right thing. # 1. After studying the Stack class and testStack() functions in stack.py # complete the Queue class below (and test it with the testQueue function) # # 2. Afer studying and testing the Circle class in circle.py, # complete the Rectangle class below (and test it with the testRectangle function) # # # 3. SUBMIT THIS ONE FILE, with your updates, TO ICON. # # # NOTE: you may certainly...

  • On the following code there is an error bc you are not reverting back to the...

    On the following code there is an error bc you are not reverting back to the original order after a sort. For the next sort you are passing the same reference variable to the next method. But that will point to the same (already sorted) array on the memory. Hence after the first sorting method, all three sorting methods are working on the already sorted array. Do the following : Just copy each data set to 4 different arrays -...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT