Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
How do recursive calls work with stacks? I have this sample code in which line B prints B 654321, c prints C, d prints D 2468 and e throws an exception. I do not understand why the program is printing those outputs! For instance, in line B, doesn't s become 0 as a result of the stack? Thank you
public class Problem1 {
public static void main(String args[]) {
Stack<Integer> s = setStack(5); printStack("A", s); // line A
s = setStack(6); stackStack(s); printStack("B", s); // line B
s = setStack(8); cutStack(s); printStack("C", s); // line C
s = setStack(8); s = cutStack(s); printStack("D", s); // line D
s = setStack(7); s = cutStack(s); printStack("E", s); // line E
}
public static Stack<Integer> setStack(int n) {
Stack<Integer> ans = new Stack<>();
for (int i = 1; i <= n; i++)
ans.push(i);
return ans;
}
public static void printStack(String tag, Stack<Integer> s) {
System.out.print(tag + " ");
while (!s.empty()) System.out.print(s.pop());
System.out.println();
}
public static Stack<Integer> cutStack(Stack<Integer> s)
{
Stack<Integer> ans = new Stack<>();
while (!s.empty()) {
ans.push(s.pop());
s.pop();
}
s = ans; return s;
}
public static void stackStack(Stack<Integer> s) {
if (s.empty()) return;
int x = s.pop();
stackStack(s);
s.push(x);
}
}
For stackStack, consider a smaller stack: 123 (with 3 on the top of the stack).
Let F1 be the first call to stackStack(), F2 be the nested call, and so on.
F1: stackStack(123) pops out the 3 and stores it in x. So x_1=3 and s=12
F2: stackStack(12) is now called. So x_2=2 and s=1
F3: Now stackStack(1) is called. Now, x_3=1 and s is empty.
Now, s is empty. So the control simply returns to F3.
F3 then pushes x_3 =1 onto the empty s. So s=1 and the control returns to F2.
F2 pushes x_2=2 onto s=1. So s=12 and the control returns to F1.
F1 pushes x_1=3 onto s=12. So s=123.
You've just ended up with the original stack and printStack() simply prints out 321.
This should give you an idea of how recursion works in general.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I tried to put f1.start(); command at the main (when i marked it with B)
and it gives me an error and i am tryin to understand why.
so i changed it to where it is now, and my program compiles as it should be,
im just curious why.
thanks.
package Try;
import java.util.Random;
import java.util.Scanner;
public class Foo1 extends Thread {
private int min_, max_;
Foo1(int max, Integer min) {
max_ = max;
min_ = min.intValue();
}
public void run() {
Random rand_gen = new Random();
while(true) {
try {
Thread.sleep(rand_gen.nextInt(max_-min_) + min_);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("you got new message");
}
}
public static void main(String[] args){
System.out.println("Insert 1 to start"); // C
Scanner sc = new Scanner(System.in); // D
int i = sc.nextInt();
if (i == 1) {
Foo1 f1;
//f1.start(); // B
int max = 1000;
Integer min = new Integer(1000);
Foo1 f2 = new Foo1(max, min);
f1 = f2; // A
f1.start();
}
}
}
Because you declared f1 but you didn't initialize the variable with an instance of Foo1.
Have a look here for more information: A Guide to Creating Objects in Java
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
class Que{
char q[];
int front , rear ;
Que(int size){
q = new char[size];
front = rear =0;
}
void push(char ch){
if(rear == q.length){
System.out.println("Que is Full");
}
else{
q[rear++]=ch;
System.out.println(ch + " Added");
}
}
void pop(){
if(front==rear){
System.out.println("Que is Empty");
}
else{
System.out.println(q[front] + " Is being popped ");
front++;
}
}
void disp(){
char temp = q[front];
for(int i = front;i<rear ; i++)
{
System.out.println(q[i]);
}
}
}
class Example{
public static void main(String args[])
throws java.io.IOException{
Que Sample1 = new Que(10);
int opt = 1;
char j,k;
while(opt!=0){
System.out.println("1-Add , 2 - Pop , 3 - Display");
j = (char) System.in.read();
if(j=='1'){
System.out.println("What to push ?");
k = (char)System.in.read();
Sample1.push(k);
}
else if(j=='2'){
Sample1.pop();
}
else if(j=='3'){
Sample1.disp();
}
else if(j=='4'){
opt = 0;
}
else{ System.out.println("Try Again");}
}
}
}
This is not working . When I compile and run it it show me the main menu and as soon as I press 1)ADD - it skips displaying 'Added' msg from the function .
What am I doing wrong?
When I press 1 (Add) it should ask me "what To Push " which it does, but then does not wait for my input and plays loop again .
So this is what displays --
1)ADD
2)Pop
3)Display
1
What to push ( takes no input)
Added (automatically displayed)
1)ADD
2)Pop
3)Display
What are you typing in your terminal ?
If you type more than one character for example 11 or even 1<Enter>, your second call to System.in.read() will immediatly return with this second character: 1 or <Enter>.
Ok, so I have a program:
public class Rec {
public static void main(String[] args) {
test(5);
}
static void test(int n) {
if (n > 0) {
System.out.println(n);
test(n-1);
System.out.println(n);
}
}
It's output is 5,4,3,2,1,1,2,3,4,5. My question is, why/how does the second println(n) statement get executed? I thought that the function call would completely cut it off, instead it acted in a way that baffles me. This isn't homework or anything, I just really am having a hard time understanding how recursion works.
All method calls return to the same place once they are done.
By effectively chaining them you get
System.out.println(5)
System.out.println(4)
System.out.println(3)
System.out.println(2)
system.out.println(1)
// If is not true now.
System.out.println(1)
System.out.println(2)
System.out.println(3)
System.out.println(4)
System.out.println(5)
Does that make sense?
When your test method terminates, it'll resume in the same place it was in the stack frame above.
For example, if I had some code:
public class Test {
public static void main(String[] args) {
System.out.println("A");
myFunc();
System.out.println("B");
}
public static void myFunc() {
System.out.println("Do something here");
}
}
...you'd expect both printlns inside main to run, since myFunc terminates/doesn't enter an endless loop.
That's true, even if you're using recursion. Your test method will eventually terminate, so that means that the second println must be executed at some point in time.
In contrast, imagine we had a "recursive" function which never terminates:
public class Test {
public static void main(String[] args) {
test2(5)
}
public static void test2(int n) {
System.out.println("A " + n);
test(n - 1);
System.out.println("B " + n);
}
}
Because the test2 method never terminates, there's absolutely no way for the second println to execute. It's for this reason why you should always design any recursive function so that it can terminate when some condition is reached.
Concept of stack is very important if we were to understand a recursion. Stack is A LIFO data structure. Remember whenever a method call happens the current state is pushed into the stack (Current state involves the values of local variables , address of next executable statement etc). Now lets see your problem.
First this happens,
System.out.println(5);
test(n-1); // method call is happening so store state to stack !!!
//stack contents: n=5 and address of next statement
System.out.println(4);
test(n-1);//another state added to stack : n =4
System.out.println(3);
test(n-1);//another state added to stack: n = 3
System.out.println(2);
test(n-1);//another state added to stack : n = 2
System.out.println(1);
test(n-1);//another state added to stack : n = 1
Now the condition if(n>0) fails now returning phase of recursion happens i.e, the control goes back to the state from which the call was made, and remember all the states were stored in stack and also remember stack is LIFO so now:
// n = 1 first state in stack
System.out.println(1);
//n = 2 second state stored in stack
System.out.println(2);
//n = 3 third state stored in stack
System.out.println(3);
//n = 4 fourth state stored in the stack
System.out.println(4);
//n = 5 last state stored in stack
System.out.println(5);
Now all the calls are completed and the control goes back to main.
Please look your code:
static void test(int n) {
if (n > 0) {
System.out.println(n);
test(n-1);// this makes the new call to method test() and causes the state to be stored in the stack
System.out.println(n);// this statement doesn't execute until the recursive call made to test() doesn't return .
}
HTH :)
To assume that your expected result should be "54321", your problem is your second
System.out.println(n);
The first part of your test-method does exactly what you want it to do:
if (n > 0) {
System.out.println(n);
test(n-1);
// System.out.println(n);
}
The result would be "54321" - fantastic!
But what happens, because of the second println-method at the end of your test-method, is that you are stacking you output actually (as Crazy Programmer already showed us really precisley). In other words: you don't need the second println-method at all to reach your goal! And that's the wonderful thing about recursion: it "breaks" when calling test() again, leaving your second println-method "not executed by now" and starts the whole process again.
What you propably don't see is, that by using
if (n > 0)
you are verifying that n is greater than 0 (so at least 1), while (at the same time) this is your break condition too! So what your method actually has to do is:
check, if n is greater than 0,
print the value of n, and (at last)
call test-method again (with n-1)
If n reaches 0, the whole "method-stacking" dissolves itself (have a look at Niels' solution) and wont return you any further n-values. Got it?
The method is still existing after the recursive call to itself. Once those calls are dealt with, the method will come back to execute the remaining lines of code.
Have a look at this : http://ideone.com/zWqP8h
public static void main(String[] args) {
test(5);
}
static void test(int n) {
if (n > 0) {
System.out.println("First step :" + n);
test(n-1);
System.out.println("Second step :" + n);
}
}
Probably it will help to clarify things.
I think you should trace code then you will get solution.
your code trace something like this. try to debug this lines this might help you.
//for n = 5
void test(int n) {
if (n > 0) {
System.out.println(n);
test(n-1);----->// call of same function
//for n = 4
void test(int n) {
if (n > 0) {
System.out.println(n);
test(n-1);----->
//for n = 3
void test(int n) {
if (n > 0) {
System.out.println(n);
test(n-1);---->
//for n = 2
void test(int n) {
if (n > 0) {
System.out.println(n);
test(n-1);---->
//for n = 1
void test(int n) {
if (n > 0) {
System.out.println(n);
test(n-1); ---->
//for n = 0
void test(int n) {
if (n > 0) {//not satisfy
System.out.println(n);
test(n-1);
System.out.println(n);
}
// Till hear you were right but next things you missed.
}//again resume of n = 1
System.out.println(n);
}
}//again resume of n = 2
System.out.println(n);
}
}//again resume of n = 3
System.out.println(n);
}
}//again resume of n = 4
System.out.println(n);
}
}//again resume of n = 5
System.out.println(n);
}
}//Finish recursion.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I've been trying to write a simple program in java to find time complexity of a program.A program whih just searches for "for" loop or "while" loop and prints the no of iteration such as O(n) or O(2n) etc.
I got the i/p program in textarea.Is there any way by which i could do the opertaion?
Please any one help me.
This is not full proof, but would work for you
import java.util.StringTokenizer;
public class Complexity {
public static void main(String[] args) {
String input = "for(i=0;i<10;i++)\n{\nfor(i=0;i<10;i++)\n{\nfor(i=0;i<10;i++)\n{\n}\n}\n}\nfor(i=0;i<10;i++)\n{\n}\nfor(i=0;i<10;i++)\n{\nfor(i=0;i<10;i++)\n{\n}\n}";
int open_bracket=0;
StringTokenizer t = new StringTokenizer(input);
String result = "";
String token="";
int current = 0;
System.out.println("CODE \n"+input);
while(t.hasMoreTokens())
{
token = t.nextToken();
if(token.equals("{")) open_bracket++;
if(token.equals("}")) open_bracket--;
if(token.length()>=3) if(token.substring(0, 3).equals("for")) current++;
if(open_bracket==0&&token.equals("}"))
{
result += " n^"+current+" +";
current = 0;
}
}
if(result.length()>0) result = result.substring(0, result.length()-1);
result = "O( "+result+")";
System.out.println("RESULT = "+result);
}
}
OUTPUT
CODE
for(i=0;i<10;i++)
{
for(i=0;i<10;i++)
{
for(i=0;i<10;i++)
{
}
}
}
for(i=0;i<10;i++)
{
}
for(i=0;i<10;i++)
{
for(i=0;i<10;i++)
{
}
}
RESULT = O( n^3 + n^1 + n^2 )
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm a beginner in Java. I have the following situation:
The ArrayList contains {10234, 20233, 34546, 43546, 59865, 70002, 92435, 200354}
And the user inputs 20000 and 50000
And I want to get values from the ArrayList between 20000 and 50000, in this case I expect 20233, 34546, 43546 as answer.
How do I do this?
This is the code I have so far:
int t1 = 20233, t2 = 59865;
int i = 0;
boolean foundt1, foundt2;
foundt1 = false;
found20 = false;
while (i < a.size && (!foundt2)) {
if (a.get(i) == 10) {
foundt1 = true;
}
if (foundt1) {
System.out.println(a.get(i));
}
if (a.get(i) == 20) {
foundt2 = true;
}
i++;
}
Here is an example of what you are trying to do.
import java.util.ArrayList;
import java.util.Arrays;
public class Test{
public static void main(String[] args) {
ArrayList<Integer> numberList = Arrays.asList(10234, 20233, 34546, 43546, 59865, 70002, 92435, 200354);
for(int nbr : numberList){ //goes through the list
if( nbr > 20000 && nbr < 50000){
System.out.println(nbr);
}
}
}
}
Hope this helps!
Best Regards, Goatcat
You can use the Guava library.
The Iterables and Range classes can solve your task.
The sample:
public static void main(String[] args) {
List<Integer> values = Arrays.asList(10234, 20233, 34546, 43546, 59865, 70002, 92435, 200354);
Iterable<Integer> filteredValues = Iterables.filter(values, Range.closed(20000, 50000));
for (Integer val : filteredValues) {
System.out.println(val);
}
}
The output is:
20233
34546
43546
You cand find more info here