Multiplying pop'd integers - java

I am writing a piece of code to pop from the Stack and multiply. I know that I can print my pop'd integers, but how do I keep track of a pop'd integer if I pop another one?
I'm trying to write a for loop with a basic counter to pop the top integer, save it to a variable, and multiply that variable to the next popped integer.
static LStack<Integer> stack = new LStack<Integer>();
static public void main (String[] args)
{
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
for(int i = stack.length(); i <= 0; i++) {
stack.pop();
}
}

You might find it easier/clearer to use a while loop:
int result = stack.pop();
while (!stack.empty()) {
result *= stack.pop();
}
If you have to use a for loop:
int result;
for (result = stack.pop(); !stack.empty();)
result *= stack.pop();
}
Regardless, the key is to initialise your end result with the top value on the stack, then multiply it by each element that you pop off the stack.

static LStack<Integer> stack = new LStack<Integer>();
/* fact() function */
public static void main(String[] args) {
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
System.out.println(calc(stack.pop()));
}
public static long calc(long n) {
if (n <= 1)
return 1;
else
return n * calc(n - 1);
}
}
This is what I ended up using, implemented the calculator from another post, it seems to work and allows me to push additional integers on. Thank you for your time everyone!

Related

How to get my function to be recursive? (Java)

I'm having to make a recursive function that will receive a stack of "int" and output the sum of the squares of the elements in the stack.
Here is what I have
public int sum_sqr_rec(Stack<Integer> stk){
int sum = 0;
for (int i=0; i<stk.size(); i++){
sum += (stk.get(i) * stk.get(i));
}
return sum;
}
The most important thing you need to determine for a recursive function is when to terminate it.
The second important thing to consider is what to return when you terminate it. When you start adding numbers, you start with sum = 0. From a recursive function, which is supposed to calculate the sum of numbers, the same value (i.e. 0) can be returned when you terminate it. Similarly, from a recursive function, which is supposed to return the product of numbers, you can return 1 on termination.
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
stack.add(2);
stack.add(3);
stack.add(4);
stack.add(5);
System.out.println(sum_sqr_rec(stack));
}
static int sum_sqr_rec(Stack<Integer> stk) {
if (stk.isEmpty()) {
return 0;
}
int n = stk.pop();
return n * n + sum_sqr_rec(stk);
}
}
Output:
54
You can use recursion like this:
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.add(2);
stack.add(2);
stack.add(4);
stack.add(5);
System.out.println(sum_sqr_rec(stack));
}
public static int sum_sqr_rec(Stack<Integer> stack) {
if (stack.isEmpty())
return 0;
return stack.peek() * stack.pop() + sum_sqr_rec(stack);
}
Note that I use Deque interface rather than Stack class directly (documentation says it should be used in preference to the Stack class).
public int recursive(Deque<Integer> stk){
if (stk.Empty()){
return 0;
}
return Math.pow(stack.pop(), 2) + recursive(stk);
}
Lots of ways to do this. But if you don't want to destroy the stack you can do it this way. The stack is restored during the return process.
n is popped. This depletes the stack of numbers and keeps n in the local call stack for later use.
The square of the element is saved on the call stack of the method in k
r is initialized for the final tally.
Once the stack is empty, simply push n back on stk and return the sums of the saved squares.
static int sum_sqr_rec(Stack<Integer> stk) {
int n = stk.pop();
int k = n*n;
int r = 0;
if (!stk.isEmpty()) {
r = sum_sqr_rec(stk);
}
stk.push(n);
return r + k;
}
Using this call sequence of statements.
System.out.println(stack);
System.out.println(sum_sqr_rec(stack));
System.out.println(stack);
Results in the following
[2, 3, 4, 5]
54
[2, 3, 4, 5]

Recursion and While Loops in Java

I'm writing a recursive program:
public static List<Integer> method(int n)
to determine whether a positive number n is the total of cubes that are positive (> 0). Example: given n = 1944 (12^3 + 6^3), the program would return the list [12, 6] in descending order. If n is not the total of cubes the program should return an empty list.
The program should return the values that start with the highest possible value for the first element, and then follow the same rule for the rest of the elements. For example, when n = 1072, the program would return [10, 4, 2] instead of [9, 7].
The method where the recursion should occur:
private static boolean method(int n, int c, LinkedList<Integer> seen)
where c is the highest number that is still allowed to be used and soFar is the list of numbers that have already been seen.
My code covers the base cases and the recursion, but I'm having issues with the loop continuing. With the input, n = 1944 my program is returning the list [12] instead of [12, 6].
public static List<Integer> method(int n)
{
LinkedList<Integer> result = new LinkedList<Integer>();
int c = (int) Math.cbrt(n);
result.add(c);
method(n, c, result);
return result;
}
private static boolean method(int n, int c, LinkedList<Integer> seen)
{
LinkedList<Integer> result = new LinkedList<Integer>();
boolean b = false;
if (n == 0)
{
return true;
}
else if (c == 0)
{
return false;
}
else
{
int sum = 0;
for (int i : seen)
{
sum += i*i*i;
}
while (b = false)
{
c = (int) Math.cbrt(n - sum);
seen.add(c);
method(n, c, seen);
if (sum == n)
{
result = seen;
return true;
}
else
{
return false;
}
}
}
return false;
}
Let's see your while loop:
LinkedList<Integer> result = new LinkedList<Integer>();
boolean b = false;
// Some code omitted here.
while (b = false)
{
c = (int) Math.cbrt(n - sum);
seen.add(c);
method(n, c, seen);
if (sum == n)
{
result = seen;
return true;
}
else
{
return false;
}
}
First, with a while loop that always has false as the condition for looping, it doesn't do anything at all.
Anyway, even if we pretend the loop runs, whatever is the branch took by the if, a return will be reached. So, your while loop doesn't loop at all even if its condition was changed to always be true. Further, the only value ever assigned for the b variable is false, and it isn't used for anything at all.
Also, the result list in the second method is always empty. And, since the result = seen; instruction is just right before the return, it is an innocuous instruction which renders the result simply being useless.
Also, look at the method(n, c, seen); call. It don't do anything with its return value! So, even if it eventually returns true, you still proceeds, which would then generate false as a result.
Also, whenever you add a value to seen, it will never be removed. Since the seen is always the very same list in every of the recursive method calls, once a bad number is added there, it will never be removed to make the way for something else.
With this, I must conclude that your algorithm is so broken that it must be rewritten from scratch.
Also, although your question isn't very clear, I presume that the numbers found must all be different. Otherwise, one could make 2 = 13 + 13 and every number larger than one could be represented by the sum of a lot of cubed ones (i.e. n = 13 + 13 + 13 + ...).
The algorithm is this:
The first step is to have a for counting i down from cbrt(n) to 1 trying to form cubes.
Then, subtract the cube from n and recursively try to find a cube sum for the resulting number.
Add a parameter to avoid repeating numbers, which is one smaller than the last number used.
When a cube is formed, return the number that formed it. In the outer calls, add the result to the list of non-empty inner recursive call.
If an inner recursive call gives an empty list as a result, then the current iteration of the for produced a bad number and we should try the next one (if we have a next one).
If the for ends without a cube forming, return an empty list.
Here is the code:
import java.util.LinkedList;
import java.util.List;
public class Main {
public static List<Integer> findCubeSum(int n) {
return findCubeSum(n, n);
}
public static List<Integer> findCubeSum(int n, int max) {
if (n <= 0) return List.of();
int c = (int) Math.cbrt(n);
for (int i = Math.min(c, max); i > 0; i--) {
int x = i * i * i;
if (x == n) {
List<Integer> result = new LinkedList<>();
result.add(i);
return result;
}
List<Integer> result = findCubeSum(n - x, i - 1);
if (result.isEmpty()) continue;
result.add(0, i);
return result;
}
return List.of();
}
public static void main(String[] args) {
System.out.println(findCubeSum(8)); // [2]
System.out.println(findCubeSum(64)); // [4]
System.out.println(findCubeSum(1000)); // [10]
System.out.println(findCubeSum(1072)); // [10, 4, 2]
System.out.println(findCubeSum(1944)); // [12, 6]
System.out.println(findCubeSum(4)); // []
System.out.println(findCubeSum(0)); // []
System.out.println(findCubeSum(-1)); // []
System.out.println(findCubeSum(10)); // []
}
}
See it running at ideone.
The code as posted has many issues. However your question is about public static List<Integer> method(int n):
public static List<Integer> method(int n) {
LinkedList<Integer> seen = new LinkedList<>();
method(n, 0, seen);
return seen;
}
Consider changing
private static boolean method(int n, int c, LinkedList<Integer> seen)
To
private static boolean method(int n, LinkedList<Integer> seen)
because you recalculate the value of c by c = (int) Math.cbrt(n);

Coins Change with Greedy algorithm

Hy guys, for some reason my greedy coins change program does not work. The function should return with the minimum amount of coins you can change a value and there is an array as well which includes the coins you can use for this. My program does not show anything an I dont know why.
public class Main {
public static int coinChangeGreedy(int[] coins, int n) {
int result = 0;
while (n != 0)
{
for (int i=coins.length - 1 ; i>=0 ; i--)
{
if (coins[i] <= n)
{
n = n - coins[i];
result++;
}
}
}
return result;
}
public static void main(String[] args)
{
int[] coins = {1, 2, 5};
int n = 11;
coinChangeGreedy(coins, n);
}
}
Well, at first - you are not printing anything - you just run the function.
Second - you have a bit of a flaw in your code. You see - if you find a coin that works, you shouldn't go to the next coin, but see if that one "fits" again.
In your example with n=11. You have 5 as the first one and then move to 2. But you should actually try the 5 again (prevent the for loop from going to the next element). See the example:
public static int coinChangeGreedy(int[] coins, int n) {
int result = 0;
while (n != 0) {
for (int i=coins.length - 1 ; i>=0 ; i--) {
if (coins[i] <= n) {
n = n - coins[i];
System.out.println("Adding " +coins[i]);
i++; //neutralizing i-- with i++.
result++;
}
}
}
return result;
}
Not you'll see that 5 is taken twice.
P.s. - if you are assuming that the coin array will be ascending.
And to print it, you just go:
System.out.println("Total coins needed: " +coinChangeGreedy(coins, n));
Additionally - if you want to keep track of coins used, you can store them in an ArrayList every time it is chosen. list.add(coins[i]). And of course you declare and initialize thatlist` at the beggining.

Loop through numbers from 0 to 100 and print out every third number without the modulo function using recursion

I had an interview the other day that asked the question, loop through the numbers from 0 to 100 and print out every third number. This is a very easy question if you know what the modulo function is. So I came up with the solution (Note I was using Java):
for (int i=0; i<100; i++) {
if (i % 3 == 0) {
System.out.println(i);
}
}
He then asked, what if you can't use division or the modulo function. So I had to think about this for about 30 seconds, and came up with a solution, that I knew was very inefficient, and let him know it was very inefficient, but would work.
int x = 3;
for (int i=0; i<100; i++) {
for (int j=0; j<33; j++) {
if (x*j==i) {
System.out.println(i);
break;
}
}
}
I'm free writing this without testing, so it might not work 100%, but you get the idea of how I solved the problem. He said he understood what I was trying to do. He then said that there is another way to do it using a recursive function. He tried to briefly explain it to me, but I didn't understand how you could use a recursive function to solve this problem. Can anyone come up with a solution using recursion?
EDIT:
Thanks for all the answers! I didn't think this question would attract as much attention as it did, but I appreciate all the answers. Some of you didn't understand that you can ONLY increment by 1. So you must loop through every natural number from 0 to 100.
There is a cool trick to test if a number is divisible by three. If the sum of all its digits is divisible by three, then the original is divisible by three. This can be applied recursively: if I have a number a, I can add all the digits of a together to get b and see if b is divisible by 3. How do I know if b is divisible by three? Add all of its digits together to get c and see if c is divisible by three...
As with all recursion, you have to stop at some point. The base case is when you have a sum which is only one digit long- you can have a list of digits divisible by three and check against these. In code:
public boolean printDivisibleByThrees(){
for(int i=0; i<100; i++){
if(isDivisibleByThree(i)){
System.out.println(i);
}
}
}
public boolean isDivisibleByThree(int i){
if(i<0){
i = -1*i; //we only care about the absolute value of i
}
if(Arrays.asList(0,3,6,9).contains(i)){
return true;
} else if(i<10){
return false; //one digit number not divisible by three
} else {
int j = sumDigits(i);
return isDivisibleByThree(j);
}
}
public int sumDigits(int i){
String iString = (new Integer(i)).toString();
int sum = 0;
for(char digit : iString.toCharArray()){
sum += (new Integer(digit+"")).intValue();
}
return sum;
}
As no answer has been picked yet I like to add my two cents here.
Since the trick is do the modulo function with recursion and without division (as I understood) here is my solution:
public static void main(String[] args) {
for ( int i = 1; i <=100; i++ ){
if ( mod(i, 3) ){
System.out.println(i);
}
}
}
public static boolean mod(int a, int b){
if ( a < 0 ){
return false;
}else if (a==b){
return true;
}else{
return mod( a-b, b );
}
}
EDIT
This version will handle division by 0 and negative numbers on the modulo function:
public static boolean mod(int a, int b){
if ( b < 0 ){
b=b*-1;
}
if ( a < 0 || b == 0){
return false;
}else if (a==b){
return true;
}else{
return mod( a-b, b );
}
}
Use a second parameter that will keep if the number is or not the third
public class Rec
{
public static void rec(int n, int t) {
if(t==3) {
System.out.println(n);
t=0; // reset it
}
if(n!=100) {
rec(++n, ++t);
}
}
public static void main (String[] args)
{
rec(0, 3);
}
}
One can define the modulus operator using recursion as follows:
// Assume a, b > 0
static int mod(a, b) {
if (a < b) {
return a;
} else {
return mod(a-b, b);
}
}
So then you could do:
for (int i=0; i<100; i++) {
if (mod(i, 3) == 0) {
System.out.println(i);
}
}
I want to add one more answer that is probably unusual, but works fine for each range.
The code is C++ (I'm from mobile and I've only a C++ compiler on it), but it is quite easy to understand and to rewrite in Java.
#include <iostream>
void foo(int c, int n) {
static int i = 0;
if(c >= n) return;
switch(i++) {
case 1:
case 2:
foo(++c, n);
break;
case 0:
case 3:
std::cout << c << std::endl;
i = 1;
foo(++c, n);
}
}
int main() {
foo(0, 100);
}
Another variation on the recursion (JavaScript code):
function f(m,i){
if (i == 100){
return;
} else if (i == 3*m){
console.log(i);
f(m + 1,i + 1);
} else {
f(m,i + 1);
}
}
f(0,0);
Why not just do:
for (int i = 0; i < 100; i += 3)
System.out.println(i);
This way you don't have to check if it is every third number, because it goes up by 3 each time.
void printNth(int max, int n, int i, int sinceLastPrinted) {
if (i>max) {
return;
}
if (sinceLastPrinted == n-1) {
System.out.println(i);
sinceLastPrinted = -1;
}
printNth(max, n, i+1, sinceLastPrinted+1);
}
printNth(100, 3, 0, 0);
It's also not 100% clear whether the last number (100 in the example) should be included (if it is "a 3rd number"), depending on that you might need to modify to:
if (i>=max) {
And also not very clear where to start the "every 3rd"? 0, 3, 6, or 2, 5, 8? The advantage of my function is that this can be easily modified by passing different value for i
This would work. !
public class Recursion {
public static void main(String[] args) {
myRecursiveMethod(0,1,100,3);
}
public static void myRecursiveMethod(int begin,int temp,int end,int n)
{
if(begin<=end)
{
if(temp==n)
{
System.out.println(begin);
temp=0;
}
myRecursiveMethod(++begin,++temp,end,n);
}
}
}

Is this a better way for Fibonacci Series with Recursion?

Where ever I see Recursive Fibonacci Series everyone tell that
a[i] = fib(i - 1) + fib( i - 2)
But it can also be solved with
a[i] = fib(i - 1) + a[i-2] // If array 'a' is a global variable.
If array 'a' is a global Variable, then a[i-2] will be calculated when it is calculating for a[i-2];
It can be solved with below program in java..
public class Fibonacci {
public static int maxNumbers = 10;
public static double[] arr = new double[maxNumbers];
public static void main(String args[])
{
arr[0] = 0;
arr[1] = 1;
recur(maxNumbers - 1);
}
public static double recur(int i)
{
if( i > 1)
{
arr[i] = recur(i - 1) + arr[i - 2];
}
return arr[i];
}
}
Further more, complexity is also less when compared with original procedure. Is there any disadvantage of doing this way?
You have done the first step for Dynamic Programming calculation of Fibonacci, idea of DP is to avoid redundant calculations, and your algorithm achieve its goal.
A "classic" Bottom-Up DP Fibonacci implementation is filling the elements from lower to higher:
arr[0] = 0
arr[1] = 1
for (int i = 2; i <= n; i++)
arr[i] = arr[i-1] + arr[i-2]
(Optimization could be storing curr,last alone, and modifying them at each iteration.
Your approach is basically the same in principle.
As a side note, the DP approach to calculate Fibonacci is taking O(n) time, where there is even more efficient solution with exponential of the matrix:
1 1
1 0
The above holds because you use the fact that
1 1 F_{n+1} 1*F{n+1} + 1*F{n} F_{n+2}
* = =
1 0 F_{n} 1*F{n+1} + 0*F{n} F_{n+1}
Using exponent by squaring on the above matrix, this can be solved in O(logn).
If you just want the nth fibonacci number you could do this:
static double fib(double prev, double curr, int n) {
if(n == 0)
return curr;
return fib(curr, prev+curr, n-1);
}
Initial conditions would be prev = 0, curr = 1, n = maxNumbers. This function is tail recursive because you don't need to store the return value of the recursive call for any additional calculations. The initial stack frame gets reused (which saves memory) and once you hit your base case the value that's returned is the same value that would be returned from every other recursive call.
By using an array like you do you only recalculate one of the two branches (the longest one in each iteration) ending up with a O(n) complexity.
If you were to keep track on how large fibonacci number you have caclulated earlier you can use that and produce O(max(n-prevn, 1)). Here is an altered version of your code that fills the array from bottom to i if needed:
public class Fibonacci {
public static final int maxNumbers = 93; // fib(93) > Long.MAX_VALUE
public static long[] arr = new long[maxNumbers];
public static int calculatedN = 0;
public static long fib(int i) throws Exception
{
if( i >= maxNumbers )
throw new Exception("value out of bounds");
if( calculatedN == 0 ) {
arr[0] = 0L;
arr[1] = 1L;
calculatedN = 1;
}
if( i > calculatedN ) {
for( int x=calculatedN+1; x<=i; x++ ){
arr[x] = arr[x-2] + arr[x-1];
}
calculatedN = i;
}
return arr[i];
}
public static void main (String args[]) {
try {
System.out.println(fib(50)); // O(50-2)
System.out.println(fib(30)); // O(1)
System.out.println(fib(92)); // O(92-50)
System.out.println(fib(92)); // O(1)
} catch ( Exception e ) { e.printStackTrace(); }
}
}
I changed double to long. If you need larger fibonacci numbers than fib(92) I would change from long to Biginteger.
You can also code using two recursive function but as the same value is calculating over again and again so all You can do a dynamic programming approach where You can store the value and return it where need.Like this one in C++
#include <bits/stdc++.h>
using namespace std;
int dp[100];
int fib(int n){
if(n <= 1)
return n;
if(dp[n]!= -1)
return dp[n];
dp[n] = fib(n-1) + fib(n-2);
return dp[n];
}
int main(){
memset(dp,-1,sizeof(dp));
for(int i=1 ;i<10 ;i++)
cout<<fib(i)<<endl;
}
This is only step from non recursive version:
https://gist.github.com/vividvilla/4641152
General this partially recursive approach looks incredibly messy

Categories

Resources