Why this recursive code repeated infinite? [closed] - 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 3 years ago.
Improve this question
I'm just calculating with recursive code, but it goes into infinite loop.
EDIT: Full code.
and IDE(Eclipse) says nothing about it, and it can be running well.
class RepresentWithN {
static int number;
static int N;
static int answer;
public int solution(int N, int number) {
RepresentWithN.N = N;
RepresentWithN.number = number;
answer = 9;
calc(0, 0);
return answer == 9 ? -1 : answer;
}
static int conN(int length) {
int tmp = N;
for (int i = 1; i < length; i++) {
tmp += tmp * 10;
}
return tmp;
}
static void calc(int prev, int count) {
if (count == 9) {
return;
}
if (prev == number) {
answer = Math.min(answer, count);
return;
}
System.out.println("count=" + count + " prev=" + prev);
for (int i = 1; i <= 5; i++) {
calc(prev + conN(i), count + 1);
calc(prev - conN(i), count + 1);
calc(prev * conN(i), count + 1);
calc(prev / conN(i), count + 1);
}
}
It repeated 'count' is around 7 or 8, and don't know why.

eventually count has the value 9. check this by printing this values.
static void calc(int prev, int count) {
System.out.println("count=" + count + " prev=" + prev);
if (count == 9) {
return;
}
...
There are so many branches in your recursion and that needs a huge amount of calculation. Thats why it is not ending. You can wait another hour or days/years to see the ends of this program. Or replace this code with efficient one.

Try this. After each run, uncomment one of the recursive calls.
public class ForEverDemo {
static long count = 0;
public static void main(String[] args) {
alongtime(0);
System.out.println("count = " + count);
}
public static void alongtime(int v) {
count++;
if (v == 9) {
return;
}
for (int i = 0; i < 3; i++) {
alongtime(v + 1);
// alongtime(v + 1);
// alongtime(v + 1);
// alongtime(v + 1);
// alongtime(v + 1);
}
}
}

Related

Printing out an array of Fibonacci numbers [closed]

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 am trying to write a recursive algorithm to compute Fibonacci numbers. However, the program struggles with printing out the results.
My idea was to store each calculated value into an array (so the algorithm should be faster).
My desired output:
The fibonacci of n = 1 is fn= 1
The fibonacci of n = 2 is fn= 2
The fibonacci of n = 3 is fn= 2
The fibonacci of n = 4 is fn= 3
...
The fibonacci of n = 8 is fn= 21
public class fibonacciCalculator {
static int[] arr = new int[50];
static int fibo (int n, int arr[]) {
if ( n == 0 ) {
return 0;
}else if ( n == 1 ) {
return 1;
}
if ( arr[n-1] == 0) {
arr[n-1] = fibo(n-1, arr);
}
if ( arr[n-2] == 0) {
arr[n-2] = fibo(n-2, arr);
}
return arr[n-1] + arr[n - 2];
}
public static void main(String[] args) {
for (int i = 1; i == 8; i++) {
if (arr [i] == 0) {
fibo(i, arr);
int x = arr[i];
String a = String.format("The fibonacci of n = %d is fn= %d", i , x);
System.out.println(a);
}
}
}
}
You can do this without declaring an array. This way, the intermediate values are stored in the execution stack:
public class fibonacciCalculator {
static int fibo (int n) {
if ( n == 0 ) {
return 0;
} else if ( n == 1 ) {
return 1;
} else {
return fibo(n-2) + fibo(n-1);
}
}
public static void main(String[] args) {
for (int i = 1; i <= 8; i++) {
int x = fibo(i);;
String a = String.format("The fibonacci of n = %d is fn= %d", i , x);
System.out.println(a);
}
}
}
Here is one way to do it.
public int[] fib(int values[], int count) {
if (count <= 0) {
return values;
}
int k = values.length + 1;
values = Arrays.copyOf(values, k);
values[k - 1] = values[k - 2] + values[k - 3];
return fib(values, count - 1);
}
But an even better way is to memoize the values as you create them. This permits you to start calculating at the last computed terms and then continue until you meet your goal. If you specify a value less than the number computed, only those requested are returned.
A defensive copy of the list is used so you can't taint the returned sublist.
List<Integer> fibs = new ArrayList(List.of(0, 1));
public List<Integer> fib(int count) {
int s = fibs.size();
if (count < s) {
// return a defensive copy to protect cached values.
return new ArrayList<>(fibs.subList(0, count));
}
int e = fibs.get(s - 1) + fibs.get(s - 2);
fibs.add(e);
return fib(count);
}
Okay to close this up I will post the working code.
Maybe that will help anyone else.
public class fibonacciCalculator {
static int[] arr = new int[48];
static int fibo (int n, int arr[]) {
if ( n == 1|| n == 2 ) {
return 1;
}else if ( n == 0 ) {
return 0;
}
if (arr[n-1] == 0) {
arr[n-1] = fibo(n-1, arr);
}
if (arr[n-2] == 0) {
arr[n-2] = fibo(n-2, arr);
}
return arr[n-1] + arr[n - 2];
}
public static void main(String[] args) {
for (int i = 1; i <= arr.length-1; i++) {
if (arr [i] == 0) {
arr[i] = fibo(i, arr);
System.out.print("The Fibonacci number " + i);
System.out.println(" is: " + arr[i]);
}
}
}
}
However ... int will exceed its limit at Fibonacci 48. If you want higher values int should be replaced to long.
but after that well don't know.. :D
Greetings Synix

I need help getting my code to look like this: [closed]

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 5 years ago.
Improve this question
I need help getting my code output to look like the image below and I am not sure what I am doing wrong and I need to have my code output indented and cant remember how to indent it.
Here is my code currently:
// Fig. 18.3: FactorialCalculator.java
// Recursive factorial method.
public class Assignment_6_1
{
// recursive method factorial (assumes its parameter is >= 0
static StringBuilder s = new StringBuilder();
public static long factorial(long number)
{
if (number == 0) // test for base case
{
return 1;
} else {// recursion step
if (s.length() == 0) {
s.append(number).append("*").append(number - 1);
} else {
for (int i = 0; i < s.length(); i++) {
}
System.out.println(number + " * " + (number - 1) + "!");
s.append("*").append(number).append("*").append(number - 1);
}
return number * factorial(number - 1);
}
}
// output factorials for values 0-21
public static void main(String[] args) {
System.out.println("Hannah Coffey - Lab 6");
// calculate the factorials of 0 through 20
for (int counter = 0; counter < 25; counter++) {
s = new StringBuilder();
System.out.println(counter + "!");
System.out.printf("%d! = %d%n", counter, factorial(counter));
}
}
} // end class FactorialCalculator
Here is what I need it to look like and not sure what I am doing wrong:
Any Help would be greatly appreciated.
My program currently looks like this:
enter image description here
You can pad a String using String.format like this :
String.format("%10s", "foo");
It will create a left padding of 7 spaces 7 + foo.length = 10;
Now, we can render that dynamic like :
public static String padding( int i ) {
return i == 0 ? "" : String.format( "%" + i + "s", "" );
}
Just pass the number of spaces and let the formatter do the job.
for(int i = 5; i >= 0; --i){
System.out.println(padding(i) + "i");
}
Output :
5
4
3
2
1
0
public static long factorial(long number){
if (number == 0) // test for base case
{
return 1;
} else {// recursion step
if (s.length() == 0) {
s.append(number).append("*").append(number - 1);
} else {
String spaces = "";
for (int i = 0; i < number; i++) {
spaces = spaces+" ";
}
if(number==1)
System.out.println(" Base Case: 1");
else {
System.out.println(spaces + "Recursive call:" + number + " * fact(" + (number - 1) + ")");
s.append("*").append(number).append("*").append(number - 1);
}
}
return number * factorial(number - 1);
}
}
public static void main(String[] args) {
System.out.println("Hannah Coffey - Lab 6");
// calculate the factorials of 0 through 20
for (int counter = 0; counter < 25; counter++) {
s = new StringBuilder();
for (int i = 0; i < counter; i++) {
spaces = spaces+" ";
}
System.out.println(spaces+"Recursive call:"+counter + "!");
System.out.printf("%d! = %d%n", counter, factorial(counter));
}
}

how to reverse the numbers in this pattern [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I wanna make a pattern like this this pattern is similar to flyords triangle but the alternate rows are in reverse order i tried something but couldn't get the expected output
1
3*2
4*5*6
10*9*8*7
11*12*13*14*15
I tried this stuff ,
public static void main(String args[])
{
int count=1;
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
if(i>j) {
System.out.print(count + "*");
count++;
}else {
System.out.print(count);count++;
}
}System.out.println();
}
}
}
the result i got is,
1
2*3
4*5*6
7*8*9*10
11*12*13*14*15
how to reverse alternate rows :(
You can determine how much to add using the trinary operator on the oddness of the line number and set the correct starting value of that line inside the definition of your for loop:
public static void main(String args[])
{
int currentNumber = 0;
for (int line = 1; line <= 5; currentNumber += (line++))
{
for (int i = 1; i <= line; i++)
{
System.out.print(currentNumber + ((line % 2 == 1) ? i : line + 1 - i));
if (i < line)
System.out.print("*");
}
System.out.println();
}
}
You can start number that would normally be last in that row for every even row. That is your starting number will be i-1 larger that it would normally be, and instead of count++ you count--.
public static void main(String args[])
{
int count=1;
for(int i=1;i<=5;i++)
{
if (i%2 == 0)
{
count += i-1; // there are i numbers on this row, highest is (i-1) larger than lowest
for(int j=1;j<=i;j++)
{
if(i>j) {
System.out.print(count + "*");
count--;
}else {
System.out.print(count);
}
}System.out.println();
count += i // count was lowest number on current row. Increase it to lowest number on next row.
}
else
{
for(int j=1;j<=i;j++)
{
if(i>j) {
System.out.print(count + "*");
count++;
}else {
System.out.print(count);count++;
}
}System.out.println();
}
}
}
int count = 1;
int plus = 0;
for (int i = 1; i <= 10; i++) {
plus = i - 1;
for (int j = 1; j <= i; j++) {
if (i % 2 == 0) {
if (i > j) {
System.out.print(count + plus + "*");
plus-=2;
count++;
} else {
System.out.print(count+plus);
count++;
}
} else {
if (i > j) {
System.out.print(count + "*");
count++;
} else {
System.out.print(count);
count++;
}
}
}
System.out.println();
}

counting multiple instances of a char (in a row) in a string [closed]

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 6 years ago.
Improve this question
No idea why my code isn't working. It keeps returning a value of 1 instead of what I expect.
public class Lab5Example
{
public static void main(String[] args)
{
System.out.println(longestRun("aabbbccd"));
System.out.println("Expected 3");
System.out.println(longestRun("aaa"));
System.out.println("Expected 3");
System.out.println(longestRun("aabbbb"));
System.out.println("Expected 4");
}
public static int longestRun(String s)
{
int count = 1;
int max = 1;
for (int i = 0; i < s.length() - 1; i += 1) {
char c = s.charAt(i);
char current = s.charAt(i + 1);
if (c == current) {
count += 1;
}
else {
if (count > max) {
count = max;
}
current = c;
}
}
return max;
}
}
Debugger isn't working right so I have no idea what's not working.
I see 3 issues.
max = count should be count = max. This is so you store the highest score found thus far.
current = c should be count = 1. This is so you reset the count to start the counting over on the next char sequence.
Outside of your loop you need to do a final check to see if the last char sequence had the highest score. if(count > max) max = count;
This would all look like:
for (int i = 0; i < s.length() - 1; i += 1) {
char c = s.charAt(i);
char current = s.charAt(i + 1);
if (c == current) {
count += 1;
}
else {
if (count > max) {
max = count; // #1
}
count = 1; // #2
}
}
if(count > max) // #3
max = count;
return max;
You want this:
if (count > max) {
max = count;
}
Instead of:
if (count > max) {
count = max;
}
Then at the end before you return add this:
if(count > max)
{
max = count;
}
return max;

Java annoying syntax error [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm new to Java and I'm trying to make an lvling system. Hers my code so far:
import java.util.*;
class Player
{
private String Name;
private int Level;
private int EXP;
int NextGoaltoLvl = 1000;
public Player(String n, int lvl, int xp)
{
Name = n;
Level = lvl;
EXP = xp;
}
public void printStats()
{
System.out.println("Name: " +Name);
System.out.println("Level: " +Level);
System.out.println("Exp: " + EXP);
}
public void addLevel(int addlvl)
{
Level += addlvl;
System.out.println("Congratulations,"+ Name +",you have leveled up to " + Level + "!");
}
public void addExp(int num)
{
EXP += num;
if (EXP == NextGoaltoLvl)
{
addLevel(1); NextGoaltoLvl += 1000; EXP = 0;
}
}
}
public class MainC
{
public static void main(String[] args)
{
Player Player01 = new Player("kert109",1,0);
for (int i = 0; i >= 10000; i++)
{
Player01.addExp(1);
}
Player01.printStats();
}
}
Player01.printStats();
I still having an error here. Says: Syntax error, insert "}" to complete ClassBody.
I have no idea whats wrong. Help? I have check ever "{" and "}". I have cleaned to code too. (Using Eclipse.)
Two errors I see:
1.
Near addExp, there is a while loop outside of the method, which is a syntax error. What's the purpose of this loop anyhow? It's an infinite loop without any breaks or returns in its body - is it actually supposed to go on forever?
2.
for (int i; i >= 10000; i++)
{
Player01.addExp(1);
}
You forgot to initialize i here. Although, this loop doesn't make sense, your condition asks if i is greater than something else and yet you increment it on each iteration (i++). What are you trying to do here?
Instead of
public void addExp(int num)
{
EXP += num;
}
while (true)
{
if (EXP == NextGoaltoLvl)
{
addLevel(1); NextGoaltoLvl += 1000; EXP = 0;
}
}
(an infinite loop? outside all function code? compile error + logic error)
I think you want
public void addExp(int num)
{
EXP += num;
if (EXP == NextGoaltoLvl)
{
addLevel(1); NextGoaltoLvl += 1000; EXP = 0;
}
}
(increment level if XP reaches new level XP)
A. R. S points out another serious issue with your for loop.
Instead of
for (int i; i >= 10000; i++)
{
You want
for (int i = 0; i <= 10000; i++)
{
or just
Player01.addExp(10000);
If what you want to do is to add 10000 XP to the player
you need to put the while loop inside of the method addExp and initialize i to 0 in one of your for loops
public void addExp(int num)
{
EXP += num;
while (true)
{
if (EXP == NextGoaltoLvl)
{
addLevel(1); NextGoaltoLvl += 1000; EXP = 0;
}
}
}
public static void main(String[] args)
{
Player Player01 = new Player("kert109",1,0);
for (int i=0; i >= 10000; i++)
{
Player01.addExp(1);
}
Player01.printStats();
}
1) For loop has an error because you have initiated int i without specifying it's initial value.
for( int i = yourInitialValue; i >= 10000; i++ )
2)
public void addExp(int num)
{
EXP += num;
}
while (true)
{
if (EXP == NextGoaltoLvl)
{
addLevel(1); NextGoaltoLvl += 1000; EXP = 0;
}
}
while loop is outside your addExp method. Where you might want it to be:
public void addExp(int num){
EXP += num;
while (true)
{
if (EXP == NextGoaltoLvl)
{
addLevel(1); NextGoaltoLvl += 1000; EXP = 0;
}
}
}
Your while loop isn't in a method. Here's a revised addExp method.
public void addExp(int num)
{
EXP += num;
if (EXP == NextGoaltoLvl)
{
addLevel(1); NextGoaltoLvl += 1000; EXP = 0;
}
}
You're also not initializing i in your main method. It's also important to note that i >= 10000 will always return false. Your for loop should probably be revised to:
for (int i = 0; i < 10000; i++)
{
Player01.addExp(1);
}

Categories