String index out of bounds - java

This is my code to add to binary strings, I am getting correct value in res string but it still gives me an exception at the end of execution.
The strings m1 & m2 are of equal length of 28 each.
Still I tried running the loop just 10 times to verify but error still persists.
This holds true for any value of i, irrespective of greater than or lesser than actual length of both strings.
public static String addMantissa(String m1,String m2)
{
String res=" ";
int c=0;
System.out.println("Length is " + m2.length());
int i=0;
while(i < m2.length())
{
System.out.print(" " + res.charAt(i));
if(m1.charAt(i)=='1' && m2.charAt(i)=='1')
{
if(c==0)
{
res+="0";
c=1;
}
else
{
res+="1";
c=1;
}
}
if(m1.charAt(i)=='1' && m2.charAt(i)=='0')
{
if(c==0)
{
res+="1";
c=0;
}
else
{
res+="0";
c=1;
}
}
if(m1.charAt(i)=='0' && m2.charAt(i)=='1')
{
if(c==0)
{
res+="1";
c=0;
}
else
{
res+="0";
c=1;
}
}
if(m1.charAt(i)=='0' && m2.charAt(i)=='0')
{
if(c==0)
{
res+="0";
c=0;
}
else
{
res+="1";
c=0;
}
}
i++;
}
return res;
}
Thanks in advance.

Your entire method can be replaced by just one line:
public static String addMantissa(String m1, String m2) {
return new BigInteger(m1, 2).add(new BigInteger(m2, 2)).toString(2);
}
The size of 28 bits mentioned in your question means that the Integer class could have neen used for parsing, but using BigInteger means that strings of any size can be handled.
You should use the JDK instead of reinventing the wheel.
Also, "less code is good" is a great mantra (provided the code remains clear, of course), and this code has high density.

#ShreyosAdikari is basically right.
System.out.print(" " + res.charAt(i));
Should be called at the end of the loop, as then res[i] is filled.
Maybe you meant:
System.out.print((" " + res).charAt(i));
But then you do not print the last loop's res.

Actually the exception comes from the line
while(i < m2.length())
You need to change it to
while(i < m2.length() && i<m1.length())
As if m1(say 1) has a length lower than m2(say 4) and you checking only the value of m2. Then in the second iteration it will enter the loop as 2<4, and when it tryes to get m1.carAt(2) (as the length 1) it will throw String index out of bounds exception.

Related

Why does for readelements() fro loop not print out?

So I've been stuck trying to get my array list to print out in the right order but it keeps printing the original input i inserted backwards for some reason, i've tried reading the array in reverse order but it doesn't work either.
public static void Add()
{
System.out.println("You may now enter your virtual diary entry...");
System.out.println("You may END the program at any time by typing in endp...\n");
boolean loop = true;
while(loop)
{
String Stop = Cons.nextLine();
if (Stop.equals("endp")| Stop.equals(""))
{
readelements();
break;
} else {
for (int i =0 ; i <= Notes.size(); ) {
Notes.add(i, Stop);
i++;
break;
}
}
}
}
public static void readelements()
{
if (Empty()) {
Empty();
}
for(int i =0; i < Notes.size(); i++) {
System.out.println(i + " = " + Notes.get(i).toString());
Notes.toString();
}
}
In your else block, you break after one iteration (when i = 0) so you're always running Notes.add(0, Stop). This prepends Stop to Notes, so Notes will be in reverse order. Removing the break will cause you to insert duplicate elements into Notes (note that you're looping but always inserting Stop). Try changing your entire else block to just Notes.add(Stop);. This will add the current value of Stop to the end of Notes and should fix your problem.

Why does my method return the wrong value?

Even though my method operationsNeeded prints the correct value for my return-int "count1", the very next line it returns something else to my main method. I did not include the rest of my code, if needed I'd gladly provide it.
For example if operationsNeeded is executed 4 times, count1 is on 4 which is printed out as well. But for reasons unknown to me the System.out.println("check: " +count1); Statement is executed 4 times like this:
check: 4
check: 4
check: 3
check: 2
I would expect my program to execute this only once and then continue to the return statement.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testcases = sc.nextInt();
int count =0;
while (count<testcases){
int numberOfColleagues = sc.nextInt();
sc.nextLine();
String startPieces = sc.nextLine();
int[] listOfcolleagues = listOfColleagues(numberOfColleagues, startPieces);
int count2 = operationsNeeded(listOfcolleagues, 1);
count++;
System.out.println(count2);
}
}
public static int operationsNeeded (int[] listOfColleagues, int count1){
//remove duplicates first
ArrayList<Integer> relevantList=removeDuplicatesAndSort(listOfColleagues);
System.out.println("relevantlist" + relevantList);
//check for smallestdelta & index
int [] deltaAndIndex = smallestDeltaHigherIndex(relevantList);
int delta = deltaAndIndex[0];
int index = deltaAndIndex[1];
if (delta==1){
for (int i=0;i<relevantList.size();i++){
if (i!=index){
relevantList.set(i,relevantList.get(i)+1);
}
}
}
if (delta>1 && delta<5){
for (int i=0;i<relevantList.size();i++){
if (i!=index){
relevantList.set(i,relevantList.get(i)+2);
}
}
}
if (delta>4){
for (int i=0;i<relevantList.size();i++){
if (i!=index){
relevantList.set(i,relevantList.get(i)+5);
}
}
}
System.out.println(count1);
int[] updatedList = new int[relevantList.size()];
for (int i=0; i<relevantList.size();i++){
updatedList[i]=relevantList.get(i);
}
if (!isAllTheSame(relevantList)) {
count1 +=1;
operationsNeeded(updatedList,count1);
}
System.out.println("check: " + count1);
return count1;
}
Your method is recursive. The "check: " line is printed on each level of that recursion, with the value that it currently has on that level. It first prints the "inner-most" value (4), than that of the level above (also 4), and finally hte value in the top-level, which is 2 after being incremented in the if above. And the value it returns is always the value from to top-level.
If you want to print it only once, you could print it on the inner-most level only, using else. However, that will still return the value from the top-level iteration; instead, keep track of the value returned from the recirsive call and update count1 accordingly.
if (! isAllTheSame(relevantList)) {
// we have to go deeper!
count1 = operationsNeeded(updatedList, count1 + 1);
} else {
// phew, finally done
System.out.println("check: " + count1);
}

Staircase problem: How to print the combinations?

Question:
In this problem, the scenario we are evaluating is the following: You're standing at the base of a staircase and are heading to the top. A small stride will move up one stair, and a large stride advances two. You want to count the number of ways to climb the entire staircase based on different combinations of large and small strides. For example, a staircase of three steps can be climbed in three different ways: three small strides, one small stride followed by one large stride, or one large followed by one small.
The call of waysToClimb(3) should produce the following output:
1 1 1,
1 2,
2 1
My code:
public static void waysToClimb(int n){
if(n == 0)
System.out.print("");
else if(n == 1)
System.out.print("1");
else {
System.out.print("1 ");
waysToClimb(n - 1);
System.out.print(",");
System.out.print("2 ");
waysToClimb(n - 2);
}
}
My output:
1 1 1,
2,
2 1
My recursion doesn't seem to remember the path it took any idea how to fix it?
Edit:
Thank you guys for the responses. Sorry for the late reply
I figured it out
public static void waysToClimb(int n){
String s ="[";
int p=0;
com(s,p,n);
}
public static void com(String s,int p,int n){
if(n==0 && p==2)
System.out.print(s.substring(0,s.length()-2)+"]");
else if(n==0 && p !=0)
System.out.print(s+"");
else if(n==0 && p==0)
System.out.print("");
else if(n==1)
System.out.print(s+"1]");
else {
com(s+"1, ",1,n-1);
System.out.println();
com(s+"2, ",2,n-2);
}
}
If you explicity want to print all paths (different than counting them or finding a specific one), you need to store them all the way down to 0.
public static void waysToClimb(int n, List<Integer> path)
{
if (n == 0)
{
// print whole path
for (Integer i: path)
{
System.out.print(i + " ");
}
System.out.println();
}
else if (n == 1)
{
List<Integer> newPath = new ArrayList<Integer>(path);
newPath.add(1);
waysToClimb(n-1, newPath);
}
else if (n > 1)
{
List<Integer> newPath1 = new ArrayList<Integer>(path);
newPath1.add(1);
waysToClimb(n-1, newPath1);
List<Integer> newPath2 = new ArrayList<Integer>(path);
newPath2.add(2);
waysToClimb(n-2, newPath2);
}
}
initial call: waysToClimb(5, new ArrayList<Integer>());
Below mentioned solution will work similar to Depth First Search, it will explore one path. Once a path is completed, it will backtrace and explore other paths:
public class Demo {
private static LinkedList<Integer> ll = new LinkedList<Integer>(){{ add(1);add(2);}};
public static void main(String args[]) {
waysToClimb(4, "");
}
public static void waysToClimb(int n, String res) {
if (ll.peek() > n)
System.out.println(res);
else {
for (Integer elem : ll) {
if(n-elem >= 0)
waysToClimb(n - elem, res + String.valueOf(elem) + " ");
}
}
}
}
public class Test2 {
public int climbStairs(int n) {
// List of lists to store all the combinations
List<List<Integer>> ans = new ArrayList<List<Integer>>();
// initially, sending in an empty list that will store the first combination
csHelper(n, new ArrayList<Integer>(), ans);
// a helper method to print list of lists
print2dList(ans);
return ans.size();
}
private void csHelper(int n, List<Integer> l, List<List<Integer>> ans) {
// if there are no more stairs to climb, add the current combination to ans list
if(n == 0) {
ans.add(new ArrayList<Integer>(l));
}
// a necessary check that prevent user at (n-1)th stair to climb using 2 stairs
if(n < 0) {
return;
}
int currStep = 0;
// i varies from 1 to 2 as we have 2 choices i.e. to either climb using 1 or 2 steps
for(int i = 1; i <= 2; i++) {
// climbing using step 1 when i = 1 and using 2 when i = 2
currStep += 1;
// adding current step to the arraylist(check parameter of this method)
l.add(currStep);
// make a recursive call with less number of stairs left to climb
csHelper(n - currStep, l, ans);
l.remove(l.size() - 1);
}
}
private void print2dList(List<List<Integer>> ans) {
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < ans.get(i).size(); j++) {
System.out.print(ans.get(i).get(j) + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
Test2 t = new Test2();
t.climbStairs(3);
}
}
Please note this solution will timeout for larger inputs as this isn't a memoized recursive solution and can throw MLE(as I create a new list when a combination is found).
Hope this helps.
if anyone looking for a python solution, for this problem.
def way_to_climb(n, path=None, val=None):
path = [] if path is None else path
val = [] if val is None else val
if n==0:
val.append(path)
elif n==1:
new_path = path.copy()
new_path.append(1)
way_to_climb(n-1, new_path, val)
elif n>1:
new_path1 = path.copy()
new_path1.append(1)
way_to_climb(n-1, new_path1, val)
new_path2 = path.copy()
new_path2.append(2)
way_to_climb(n-2, new_path2, val)
return val
Note: it is based on the #unlut solution, here OP has used a top-down recursive approach. This solution is for all people who looking for all combination of staircase problem in python, no python question for this so i have added a python solution here
if we use a bottom-up approach and use memorization, then we can solve the problem faster.
Even though you did find the correct answer to the problem with your code, you can still improve upon it by using just one if to check if the steps left is 0. I used a switch to check the amount of steps taken because there are only 3 options, 0, 1, or 2. I also renamed the variables that were used to make the code more understandable to anyone seeing it for the first time, as it is quite confusing if you are just using one letter variable names. Even with all these changes the codes run the same, I just thought it might be better to add some of these things for others who might view this question in the future.
public static void climbStairsHelper(String pathStr, int stepsTaken, int stepsLeft)
{
if(stepsLeft == 0)
{
switch(stepsTaken)
{
case 2:
System.out.print(pathStr.substring(0, pathStr.length() - 2) + "]");
break;
case 1:
System.out.print(pathStr + "");
break;
case 0:
System.out.print("");
break;
}
}
else if(stepsLeft == 1)
{
System.out.print(pathStr + "1]");
}
else
{
climbStairsHelper(pathStr + "1, ", 1, stepsLeft - 1);
System.out.println();
climbStairsHelper(pathStr + "2, ", 2, stepsLeft - 2);
}
}`
`

trying to break out of for loop but keeps going back into it and performing recursive call

I just discovered the project euler website, I have done challenges 1 and 2 and have just started number 3 in java... here is my code so far:
import java.util.ArrayList;
public class IntegerFactorise {
private static int value = 13195;
private static ArrayList<Integer> primeFactors = new ArrayList<Integer>();
private static int maxPrime = 0;
/**
* Check whether a give number is prime or not
* return boolean
*/
public static boolean isPrimeNumber(double num) {
for(int i = 2; i < num; i++) {
if(num % i == 0) {
return false;
}
}
return true;
}
/*Multiply all of the prime factors in the list of prime factors*/
public static int multiplyPrimeFactors() {
int ans = 1;
for(Integer i : primeFactors) {
ans *= i;
}
return ans;
}
/*Find the maximum prime number in the list of prime numbers*/
public static void findMaxPrime() {
int max = 0;
for(Integer i : primeFactors) {
if(i > max) {
max = i;
}
}
maxPrime = max;;
}
/**
* Find all of the prime factors for a number given the first
* prime factor
*/
public static boolean findPrimeFactors(int num) {
for(int i = 2; i <= num; i++) {
if(isPrimeNumber(i) && num % i == 0 && i == num) {
//could not possibly go further
primeFactors.add(num);
break;
}
else if(isPrimeNumber(i) && num % i == 0) {
primeFactors.add(i);
findPrimeFactors(num / i);
}
}
int sumOfPrimes = multiplyPrimeFactors();
if(sumOfPrimes == value) {
return true;
}
else {
return false;
}
}
/*start here*/
public static void main(String[] args) {
boolean found = false;
for(int i = 2; i < value; i++) {
if(isPrimeNumber(i) && value % i == 0) {
primeFactors.add(i);
found = findPrimeFactors(value / i);
if(found == true) {
findMaxPrime();
System.out.println(maxPrime);
break;
}
}
}
}
}
I am not using the large number they ask me to use yet, I am testing my code with some smaller numbers, with 13195 (their example) i get down to 29 in this bit of my code:
else if(isPrimeNumber(i) && num % i == 0) {
primeFactors.add(i);
findPrimeFactors(num / i);
}
}
int sumOfPrimes = multiplyPrimeFactors();
if(sumOfPrimes == value) {
return true;
}
It gets to the break statement then finally the check and then the return statement.
I am expecting the program to go back to the main method after my return statement, but it jumps up to:
findPrimeFactors(num / i);
and tries to finish the iteration...I guess my understanding is a flawed here, could someone explain to me why it is behaving like this? I can't wait to finish it of :) I'll find a more efficient way of doing it after I know I can get this inefficient one working.
You are using recursion, which means that a function will call itself.
So, if we trace what your function calls are when you call return, we will have something like that:
IntegerFactorise.main()
|-> IntegerFactorise.findPrimeFactors(2639)
|-> IntegerFactorise.findPrimeFactors(377)
|-> IntegerFactorise.findPrimeFactors(29) -> return true;
So, when you return in the last findPrimeFactors(), you will only return from this call, not from all the stack of calls, and the execution of the previous findPrimeFactors() will continue just after the point where you called findPrimeFactors().
If you want to return from all the stack of calls, you have to modify your code to do something like that:
else if(isPrimeNumber(i) && num % i == 0) {
primeFactors.add(i);
return findPrimeFactors(num / i);
}
So that when the last findPrimeFactors() returns, all the previous findPrimeFactors() which called it will return too.
I think the problem is that you are ignoring the return value from your recursive call to findPrimeFactors().
Let's walk through this. We start with the initial call to findPrimeFactors that happens in main. We then enter the for loop as it's the first thing in that method. Now let's say at some point we get into the else statement and thus recursively call frindPrimeFactors(num / i). This will suspend the looping, but as this recursive call starts to run you enter the for loop again (remember, the previous loop is merely paused and not finished looping yet). This time around you encounter the break, which allows this recursive call to finish out, returning true of false. When that happens you are now back to the original loop. At this point the original loop continues even if the recursive call returned true. So, you might try something like this:
if (findPrimeFactors(num / i))
return true;
I'm assuming that you need to continue looping if the recursive call returned false. If you should always finish looping upon return (whether true or false) then try this:
return findPrimeFactors(num / i);

Recursively splitting off perfect squares for display

I am attempting to create a recursive method that accepts an integer parameter and prints the first n squares
separated by commas, with the odd squares in descending order followed by the even squares in ascending order.
For example, if the input is 8, it should print the following output:
49, 25, 9, 1, 4, 16, 36, 64
My code so far is:
s and n have the same values initially, the only difference is that s changes as the code forwards while n doesn't change.
private static void genSquare(int s, int n) {
if (s >= 0 && s <= n) {
if (isOdd(s)) {
System.out.print(Math.pow(n, 2) + " ");
genSquare(s - 2, n);
}
if (s == 0 || s == 1) {
genSquare(1, n);
}
if (isEven(s)) {
System.out.print(Math.pow(n, 2) + " ");
genSquare(s + 2, n);
}
}
}
I have created a while loop version of it, which works perfectly. I just don't have the recursive version working.
Sample inputs would be using the same number for s and n.
Here is the code for the loop version:
private void genLoop(int s, int n) {
if (isEven(s)) {
s--;
}
while (s <= n) {
if (s == 1) {
System.out.print(1 + " ");
s++;
} else if (isOdd(s)) {
System.out.print(s * s + " ");
s -= 2;
} else if (isEven(s)) {
System.out.print(s * s + " ");
s += 2;
}
}
}
The problem is in this statement:
if(s == 0 || s== 1)
genSquare(1,n);
This causes the method to recurse infinitely. In fact, when you get to the point where s is zero or one, you have to make sure that you DON'T call genSquare recursively.
That's enough of a hint for you to figure the rest out for yourself ... and fix any other bugs.
In addition, there's a simpler way of squaring an integer ...
void calculateSquare(int n)
{
// odds descending and even ascending
int t=n;
if(n<=0)
return;
if(n%2==1)
{
// Calculate square now and print it also
System.out.println(n*n);
calculateSquare(--n);
}
else
{
calculateSquare(--n);
System.out.println(t*t);
}
}
This would do the job.
Try the following approach:
Assume your example where n is equal to 8. The square of 8 should printed last so you probably first should do a recursive call, then print the square of the current number.
Thinking about the task for n=7 the order of things given above should be reverted for odd numbers.
Yes it is good example for recursion . Try this it helps u
public class RecursionEx {
static int no = 0;
public static void main(String[] args) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Number");
try
{
no = Integer.parseInt(bufferedReader.readLine());
getSquares(no,0);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static void getSquares(int number,int count)
{
if(number==1)
{
System.out.print(number);
count=1;
getSquares(number+1, count);
}
else
{
if(number%2!=0&&count==0)
{
System.out.print(number*number+",");
getSquares(number-2,0);
return;
}
if(count==0)
getSquares(number-1,0);
if(number%2==0&&count==1)
{
if(number<=no)
System.out.print(","+number*number);
if(number>=no)
return;
getSquares(number+2, count);
}
}
}
}

Categories