Permutations Code not working Java - java

My teacher gave me some java code and asked me to rewrite it in python. I'm not asking for help with rewriting it, but when I entered the code into my Java compiler I got this error:
Exception in thread "main" java.lang.StackOverflowError
at
java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:449)
at java.lang.StringBuilder.append(StringBuilder.java:136)
at java.lang.StringBuilder.<init>(StringBuilder.java:113)
at Permutations.perm1(Permutations.java:12)
at Permutations.perm1(Permutations.java:4)
Any help is greatly appreciated, here is the code:
public class Permutations {
public static void perm1(String s) {
perm1("", s);
}
private static void perm1(String prefix, String s){
int N=s.length();
if(N==0){
System.out.println(prefix);
}else{
for(int i=0; i<N; i++){
perm1(prefix+s.charAt(i)+s.substring(0, i)+s.substring(i+1,
N));
}
}
}
public static void perm2(String s){
int N=s.length();
char[] a = new char[N];
for(int i=0;i<N;i++){
a[i]=s.charAt(i);
perm2(a,N);
}
}
private static void perm2(char[] a, int n){
if(n==1){
System.out.println(a);
return;
}
for(int i=0; i<n;i++){
swap(a,i,n-1);
perm2(a,n-1);
swap(a,i,n-1);
}
}
private static void swap(char[] a, int i, int j) {
char c;
c=a[i];
a[i]=a[j];
a[j]=c;
}
public static void main(String[] args) {
int N=5;
String alphabet="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String elements = alphabet.substring(0,N);
perm1(elements);
System.out.println();
perm2(elements);
}
}

There is an error in this line:
perm1(prefix+s.charAt(i)+s.substring(0, i)+s.substring(i+1,
N));
Should look like this:
perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i + 1, N));
Compere with this code:
http://introcs.cs.princeton.edu/java/23recursion/Permutations.java.html

Stepping through the code with a debugger shows that you get a stack overflow error because of this section:
for(int i=0; i<N; i++){
perm1(prefix+s.charAt(i)+s.substring(0, i)+s.substring(i+1,N));
}
perm1 is called repeatedly, but the input doesn't change - it's always passed "abcde" with no prefix, and the result of prefix+s.charAt(i)+s.substring(0, i)+s.substring(i+1,N) is still "abcde". Since the call is recursive, and the input doesn't change with each iteration, it just repeats and takes up increasingly more space on the stack until it overflows and throws an exception.

Related

How do I pass the array to the main method after calculating the sum of values?

So this is the code I currently have. I am trying to calculate the sum of all the numbers in the second method and then return it to the main method to display but I am getting confused with how to do this properly. Any help is welcome!
public class Main {
public static void main(String[] args) {
int[] population = {
693417,
457502,
109985,
107360,
103773,
13145,
5469
};
int[] total = computeTotal(population);
for (int i = 0; i < total.length; i++);
System.out.print(total + " ");
}
public static int computeTotal(int[] population) {
int[] population2 = {
693417,
457502,
109985,
107360,
103773,
13145,
5469
};
return population2;
}
}
If want to calculate sum via method, you can just return an integer.
public static void main(String[] args) {
int[] population = { 693417, 457502, 109985, 107360, 103773, 13145, 5469 };
int total = computeTotal(population);
System.out.print(total + " ");
}
public static int computeTotal(int[] Popu) {
int sum=0;
for(int i=0;i<Popu.length;i++)
sum+=Popu[i];
return sum;
}
By the way the for loop you write is going to do nothing because it just run length times with no command according to ; is the first command each time the executing loop see .
You should write like this
for(int i=0;i<Popu.length;i++)
only one line code end with ;
or
for(int i=0;i<Popu.length;i++){
...
}
to run mutiple code.

StackOverflow Error in program and I cant find the reason

void recur(int i)
{
if(i==n)
return;
String sub="";
for(int j=i+1;j<n;j++)
{
sub=s.substring(i,j);
if(isPalindrome(sub))
System.out.println(sub);
}
recur(i++);
}
I am encountering a StackOverflowError at the
sub=s.substring(I,j);
statement.
s="geeks", initial value of I=0;
recur(i++);
The value of the expression i++ is the value of i at the current time; and afterwards you increment it.
As such, you are basically invoking:
recur(i);
i++;
And so you are just invoking recur again with the same parameter.
Try:
recur(++i);
Try This
public class P {
public static final String s="geeks";
static void recur(int i){
int n=6; //Size of string
if(i==n)
return;
String sub="";
for(int j=i+1;j<n;j++)
{
sub=s.substring(i,j);
//Any Function
System.out.println(sub);
}
recur(++i);
}
public static void main(String[] args) {
P.recur(0);
}
}

printStars method with recursion

Here are my instructions:
Write a recursive method called printStar(int n) which will print the following when n=4:
****
***
**
*
*
**
***
****
This is what I did so far:
public class Stars{
public static void main (String[] args){
printStars(4);
}
public static void printStars(int count){
if (count==0){
System.out.println("");
}
else{
System.out.print("*");
printStars(count-1);
}
}
}
My attempt only prints one line of the given number of stars. I don't know how to print multiple lines with only one call of the method. Any help is appreciated.
This one uses tail recursion, is split into helper function, and uses loop only to get the character as required.
public class JavaR {
public static void main(String[] args) {
System.out.println(star(4, new StringBuilder()));
}
public static StringBuilder star(int times, StringBuilder builder) {
return getStars(times, builder, times);
}
public static StringBuilder getStars(int currentIteration, StringBuilder builder, int times) {
if (currentIteration < -1 * times) return builder;
else if (currentIteration != 0) {
builder.append(getNTimes(Math.abs(currentIteration)));
return getStars(currentIteration - 1, builder, times);
} else {
return getStars(currentIteration - 1, builder, times);
}
}
public static String getNTimes(int count) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < count; i++) {
builder.append("*");
}
return builder.append("\n").toString();
}
}
Your program is incorrect, see the below program and analyze it -
public class Stars{
public static void main (String[] args){
printStars(4);
}
public static void printStars(int count){
if (count==0){
// System.out.println("");
}
else{
int tempCount = count;
while(tempCount>0){
System.out.print("*");
tempCount--;
}
System.out.println();
printStars(count-1);
while(tempCount<count){
System.out.print("*");
tempCount++;
}
System.out.println();
}
}
}
Explanation - I am using two while loops to print stars, first to print the start in asc order and second to print in reverse order. Using variable tempCount to get the current counter.
Try this
public static void printStars(int count){
if (count == 0){
return;
}
printStarNTimes(count);
printStars(count-1);
printStarNTimes(count);
}
private static void printStarNTimes(int n) {
for (int i = 0; i < n; i++) {
System.out.print("*");
}
System.out.println();
}
Logic is in printing star count times in the current call and when the recursive call returns.
The method needs information about the max number of *, as well as direction (is number of * increasing or decreasing)
Since the requested method signature includes only one argument, you have a few alternatives to define the additional needed information:
Use a partially recursive method like in this and this answers, or use a helper method:
public static void printStars(int count){
printStars(count, count, -1);
}
public static void printStars(int count , int max, int increment){
for(int i =0; i< count; i++) {
System.out.print("*");
}
count += increment;
if(count ==0 ) { //lower limit reached
increment = -increment;
}else {
System.out.println("");
}
if (count > max){ //upper limit reached
return;
}
printStars(count, max, increment);
}

BIT is not showing the correct value

I am having a String , i am creating a BIT of String based on the frequency of the element present
String:
abcdbcaab
Code:
class Test{
static int[][] dp;
public static void update(int i , int val ,int[] dpp){
while(i<=100000){
dpp[i]+=val;
i+= (i&-i);
}
}
public static int value(int i ,int[] dp){
int ans =0;
while(i>0){
ans+=dp[i];
i-= (i&i);
}
return ans;
}
public static void main(String args[] ) throws IOException {
Scanner in = new Scanner(new InputStreamReader(System.in));
dp = new int[27][1000001];
String s = in.next();
for(int i=0;i<s.length();i++){
update(i+1,1,dp[s.charAt(i)-'a']);
}
System.out.println(dp[0][7]); // Should show 2 as the frequency of 'a' at 7 position is 2
}
}
Where i am doing wrong . i could not get it but dp[0][8] is showing me 3Please Help i could not figure it out where i have commit mistake
Negativity should be avoided in life !!! but i think a little more negativity can improve you'r code:
value function you are doing wrong decrement of value of i
public static int value(int i ,int[] dp){
int ans =0;
while(i>0){
ans+=dp[i];
i-= (i&i); // Should be (i&-i);
}
return ans;
}

'.class.' error in java

I tried a problem which worked fine on C++; here is the C++ implementation.
#include<iostream>
#include<string>
#include<string.h>
using namespace std;
int main()
{
int t;
char str[1000100];
char num[1010];
cin>>t;
while(t--)
{
cin>>num;
cin>>str;
int a=strlen(str);
int b=strlen(num);
int x=0;
int flag=0;
int m=0;
for(int j=0;j<2*b;j++)
{
if(m==b)
{
flag=1;
m--;
}
if(m==0)
{
flag=0;
}
num[j]=num[m];
if(flag==0)
m++;
if(flag==1)
m--;
}
for(int i=0;i<a;i++)
{
if(x==2*b)
x=0;
if((str[i]-(num[x]-'0'))<97)
str[i]=char(str[i]-(num[x]-'0')+26);
else
str[i]=char(str[i]-(num[x]-'0'));
x++;
}
cout<<str<<endl;
//cout<<num;
}
return 0;
}
Here is my Java implementation.
import java.util.Scanner;
class sngmsg
{
public static void main(String[] s)
{
Scanner sc=new Scanner(System.in);
int t;
/*char[] str;
str = new char[1000100];
char[] num=new char[1010];*/
String str;
String num;
char[] num1=new char[1010];
char[] str1=new char[1000100];
t=sc.nextInt();
for(int l=0;l<t;l++)
{
num=sc.next();
str=sc.nextLine();
int a=str.length();
for(int c=0;c<a;c++)
str1[c]=str.charAt(c);
int b=num.length();
int x=0;
int flag=0;
int m=0;
for(int j=0;j<2*b;j++)
{
if(m==b)
{
flag=1;
m--;
}
if(m==0)
{
flag=0;
}
num1[j]=num.charAt(m);
if(flag==0)
m++;
if(flag==1)
m--;
}
for(int i=0;i<a;i++)
{
if(x==2*b)
x=0;
if(int(str1[i])-(num1[x])<97)
str1[i]=char(int(str1[i])-num1[x])+26);
else
str1[i]=char(str1[i]-(num1[x]-'0'));
x++;
}
}
}
}
In the section
if(int(str1[i])-(num1[x])<97)
str1[i]=char(int(str1[i])-num1[x])+26);
else
str1[i]=char(str1[i]-(num1[x]-'0'));
x++;
it is giving an error:
unexpected type
required:value
found: class
'.class' expected
; expected
and similar errors in these lines.
Any help?
it should be
if((int)(str1[i])-(int)(num1[x])<97)
cast operator should have () over them like (int) 1 and (char) 'a' instead of int(1) or char('a')
int and char aren't functions, but are primitives.
str1[i]=char(int(str1[i])-num1[x])+26)
You're trying to use int as a function. What do you expect from it?
Usualy, you will have a public class with your main method. It seems that you are compiling your class and you are not able to execute it. Do this to solve your problem:
1 - Create a file with your class name, example "MyClass.java"
2 - Your class declaration needs to be public:
public class MyClass {
// your code here
}
3 - Place your main method inside the created class:
public class MyClass {
public static void main( String[] args ) {
// your code here
}
}
4 - Compile it (javac MyClass.java)
5 - Execute it: java MyClass
Your code seems to have some problems too. If you want to cast some primitive or reference type, you need to put the desired type inside parenthesis. Something like:
// a char
char c = 'a';
// casting that char to an integer
int i = (int) c;
Let me know if it worked.
You are missing a package name at the start of the file. Also the class should be public.
package something.somethingelse;
import java.util.Scanner;
public class sngmsg{

Categories