I'm trying to write a program that uses recursive method find number of paths from start of two dimension array to the end . The steps should start from [0][0] till the end . Array is filled by int number between 0 to 99 .
For every number in the array can be two different steps forward : for example if [0][0] is 21 , next step could be [0+2][0+1] or [0+1][0+2] .
The method should return number of different paths to get to the final point .
Here is my code :
During the comilation a have overflow when the method gets [][] array
public class two
{
int[][] _my=new int[0][0];
public two ()
{
}
static int count=0;
public static int count;
ountPath(int[][] mat)
{
int nextX=0;
int nextY=0;
int current=mat[0][0];
if (current<=9)
{
nextX=current;
nextY=current;
if (checkBorders(0,0,nextX,nextY,mat)==0)
{
return 0;
}
}
else
{
nextX=(int)current/10;
nextY=current%10;
if (checkBorders(0,0,nextX,nextY,mat)==0)
{
return 0;
}
}
countPath(mat,nextX,nextY);
countPath(mat,nextY,nextX);
return count;
}
public static int countPath(int[][] mat,int x,int y)
{
int current=mat[x][y];
int nextX=0;
int nextY=0;
int terminate=0;
if (current<=9)
{
nextX=current;
nextY=current;
if (checkBorders(x,y,nextX,nextY,mat)==0)
{
return 0;
}
}
else
{
nextX=(int)current/10;
nextY=current%10;
if (checkBorders(x,y,nextX,nextY,mat)==0)
{
return 0;
}
}
if (((mat.length-1)==nextY)&&((mat[0].length-1)==nextX))
{
terminate=1;
}
if (terminate==1)
count++;
else
{
countPath(mat,nextX,nextY);
countPath(mat,nextY,nextX);
}
return count;
}
public static int checkBorders(int x,int y,int x1,int y1,int[][] mat)
{
int maxX=mat[0].length;
int maxY=mat.length;
if ((x+x1)>maxX)
return 0;
else if ((y+y1)>maxY)
return 0;
else return 1;
}
}
Please help me to fix the code.
You have to add one more array of bool where u will store which state have already been visited. Now you may come to following scenario:
You are in state A.
From state A you can go to states B and C.
From state B you can go to state A <- this will be infinite loop.
Also the memorization will increase calculation speed drastically.
Hope I helped you.
Related
I'm trying to print all the permutations of a string. But, despite my best efforts i'm not able to get the required output for my code. Can someone explain me what's wrong with my code? I've been trying this for many hours and failed miserably.
The output for the below code is:-
abc
This is the permute function for backtrack:-
int i, l = 2;
void permute(String str, int n)
{
for(i=n;i<=l;i++)
{
if(n==l)
{
System.out.println(swap(str,n,i));
return;
}
else
permute(swap(str,n,i),n+1);
}
}
This is the main function that runs the above code:-
public static void main(String args[])
{
BacktrackTest bt=new BacktrackTest();
String c="abc";
bt.permute(c,0);
}
This is the code for swap:-
String swap(String st, int s1, int s2)
{
char chr[] = st.toCharArray();
char t;
t = chr[s1];
chr[s1] = chr[s2];
chr[s2] = t;
st = String.valueOf(chr);
return st;
}
Don't define i outside of permute method. Try this:
int l = 2;
void permute(String str, int n)
{
for(int i=n;i<=l;i++)
{
if(n==l)
{
System.out.println(swap(str,n,i));
return;
}
else
permute(swap(str,n,i),n+1);
}
}
If you declare i outside the for loop, it's value is not "restored" for the caller after the return.
In your example, when you enter if(n==l), the value of i is 2, but after you return; it is still 2 because of its global scope. So in the next iteration it gets increased to 3, thus i<=l turns out false and the program ends.
If you declare i it inside the loop, after you return; it will be back at 1 so the loop can continue.
I have the task to build a method to search for an identical value for a variable in an array.
When there is a match, the method will return the index-Position, otherwise it should return -1.
My method works when there is a match, but I get an error when there isnĀ“t any match.
My Code so far:
public class Schleifentest {
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] cherry = {7,5,6,8,9};
int magNumber = 112;
int enthalten2 = Schleifentest.sucheWhile(cherry, magNumber);
System.out.println(enthalten2);
}
public static int sucheWhile(int [] array, int a) {
int i = 0;
while(i <= array.length) {
if (array[i] == a) {
return i;
}
i++;
}
// here is the problem
return -1;
}
}
Thanks for your help.
Phil
it should be
while(i < array.length) {...}
suppose that the array has 10 elements. They are indexed from 0 to 9. When you reach the end, with your code, you'll consider the one indexed as 10, that doesn't exist, and you have the error.
I am able to create a Max Heap using a function heapify() but when i try to call it again(to delete max and create a sorted array) the program gets stuck/doesn't stop taking input. What's wrong?
Is this a memory problem?If I increase the number of calls by increasing the frequency of for loop it still works fine.
public class HeapSort
{
int[] heap;
public void sort(int length)
{
int temp;
for(int i=length;i>=1;i--)
{
heapify(i,length);
}
//if I try to call heapify again(even once) after this,the program gets stuck
}
public void heapify(int i,int l)
{
int lchild=2*i,rchild,max;
int temp;
while(lchild<=l)
{
rchild=(2*i)+1;
if(rchild<=l)
max=(heap[lchild]>heap[rchild])? lchild:rchild;
else
max=lchild;
if(heap[i]<heap[max])
{
temp=heap[i];
heap[i]=heap[max];
heap[max]=temp;
i=max;
}
lchild=2*i;
}
}
public static void main(String args[]) throws IOException
{
BufferedReader r= new BufferedReader(new InputStreamReader(System.in));
int length=Integer.parseInt(r.readLine());
HeapSort Heap=new HeapSort();
Heap.heap=new int[length+1];
for(int i=1;i<=length;i++)
Heap.heap[i]=Integer.parseInt(r.readLine());
Heap.sort(length);
for(int i=1;i<=length;i++)
System.out.print(Heap.heap[i]+" ");
}
}
Heapify should be done for length/2 iterations because it is like a tree structure.
Here is a complete code for heap sort...This sort array 's'
public class HeapSort {
public static void main(String[] args) {
String s[]={"aaaa","dddd","cccc","gggg","bbbbb"};
AsHeap(s);
HeapSort(s);
for(String x:s){
System.out.println(x);
}
}
public static void AsHeap(String s[]){
for( int i = s.length / 2; i >= 0; i-- ){
DownHeap( s, i, s.length );
}
}
public static void HeapSort(String[] s){
for(int i=s.length-1;i>0;i--){
swap(s,0,i);
DownHeap(s,0,i);
}
}
public static int getLeftChildIndex(int i){
return 2 * i + 1;
}
private static void DownHeap(String[] s, int i, int length) {
int indexOfChild;
String temp;
for(temp=s[i];getLeftChildIndex(i)<length;i=indexOfChild){
indexOfChild=getLeftChildIndex(i);
if(indexOfChild !=length-1 && s[indexOfChild].compareTo(s[indexOfChild+1])<0){
indexOfChild++;
}
if(temp.compareTo(s[indexOfChild])<0){
s[i] = s[indexOfChild];
} else{
break;
}
}
s[i] = temp;
}
public static void swap(String s[],int x,int y){
String temp=s[x];
s[x]=s[y];
s[y]=temp;
}
}
The while loop isn't terminating when there is no swap between the parent and the child(i.e. the parent is greater than the child).
The value of i(just above main method) doesn't change when parent is greater. Simply taking the line i=max outside the if block [if(heap[i]
Also,is there any sequence to learn Algorithms?If so,kindly guide me.
Thank you.
Here I am working on the following problem where we are given n types of coin denominations of values v(1) > v(2) > ... > v(n) (all integers) The following code tries to find the minimum number of coins that are required to make a sum-C. Here the C is 100(see main function).When I run the code, error--"java.lang.StackOverflowError" comes. Please help.
import java.util.ArrayList;
public class Problem2 {
public static int count=4;
public static int []v={25,10,5,1}; //Array storing denominations
private static int findminimum(ArrayList<Integer> v2) {
int count=v2.get(0);
for(int i=0;i<v2.size();i++)
{
if(count>v2.get(i))
{
count=v2.get(i);
}
}
return count;
}
public static int countmincoins(int n)
{
int t;
if(n<0)
{
t=Integer.MAX_VALUE-100 ;
}
if(n==0)
{
t= 0;
}
else
{
ArrayList<Integer> a=new ArrayList<Integer>();
for(int i=0;i<v.length;i++)
{
int temp=0;
temp=countmincoins(n-v[i])+1; //Stackoverflow error
a.add(temp);
}
t=findminimum(a);
}
return t;
}
public static void main(String args[])
{
System.out.println(countmincoins(100));
}
}
If you use recursion then you need to reach a condition to terminate the recursion. But in your code I do not seen any termination logic. Thats why, it get to infinite loop and StackOverflowException. In your code you use following code to terminate.
if(n==0)
{
t= 0;
}
But here n may not be zero. Becuase countmincoins(n-v[i]) do not ensure you to n will be 0.
Your code is infinite cause t will never be <0 or ==0 given that the values in the array and the condition (n - v[i] )+1, v[i] will always return the same value in every call to the method, therefore infinite recursion.
If your not restricted to using recursion the following would be much simpler:
public static int[] denominations = {25,10,5,1};
public static int minimumCoins(int amount){
int total = 0;
for(int denomination: denominations){
while(amount - denomination >= 0){
amount -= denomination;
total++;
}
}
return total;
}
public static void main(String args[])
{
System.out.println(minimumCoins(98));
}
I am attempting to create a program which finds values which are both "triangle numbers" and "star numbers". However I am slightly confused about when the program branches to the second function etc. Any help is appreciated!
public class Recursion {
public static void main(String[] args) {
// TODO Auto-generated method stub
int count =0;
int n = 1;
int t=0;
int triangularNumber =0;
while (n<Integer.MAX_VALUE)
{
t = isTriangularNumber(n,count,triangularNumber);
triangularNumber=0;
int starNumber= ((6*n)*(n-1)) + 1;
if (starNumber ==t)
{
System.out.println(t);
}
n++;
}
if (n==Integer.MAX_VALUE)
{
System.exit(0);
}
}
public static int isTriangularNumber(int n, int count, int triangularNumber)
{
triangularNumber =triangularNumber + (n-(n-count));
if (count<=n)
{
return isTriangularNumber(n,(count++), triangularNumber);
}
else return triangularNumber;
}
}
return isTriangularNumber(n,(count++), triangularNumber);
In the above invocation, count++ is evaluated to count only. So, on every invocation, you are actually passing unchanged value of count. And hence the if condition: -
if (count<=n)
will always be evaluated to true, if it is true for the first invocation. Thus filling the stack with infinite method invocation.
Your invocation should be with ++count: -
return isTriangularNumber(n,(++count), triangularNumber);