How to resolve time out error in my java code - java

How to resolve timeout error in my java code:
This code first finds reverse of the element and then find out the difference between the actual and reverse value if that difference is divisible by k then increase the counter
Please find below code :
//all header files are included
public class Solution {
// Complete the beautifulDays function below.
static int beautifulDays(int i, int j, int k) {
int count=0;
for(int a=i;a<=j;a++)
{
int p=a;
int t=0,r=0;
while(a>0)
{
r=a%10;
t=t*10+r;
a=a/10;
}
if((t-p)%k==0)
count++;
}
return count;
}
// all other code of input and calling methods

You have an infinite loop in this section:
for (int a = i; a <= j; a++) {
int p = a;
int t = 0, r = 0;
while (a > 0) {
r = a % 10;
t = t * 10 + r;
a = a / 10; //OUCH!
}
}
Lets analyze this.
The outer loop increases the loop variable a by 1 from i to j
The inner loop decreases the same loop variable a until it reaches zero.
Guess which one wins? (Can't guess? Try a pencil and paper and "hand execute" these loops. It is a useful exercise.)
That means .... that the outer loop will never terminate.
Solution: use a different loop variable in the inner loop.

Related

2D array filling | ArrayIndexOutOfBoundsException error

good afternoon! hi all! 1st time posting
for my assignment we are filling arrays using arithmetic and nested for loops. i've done a complete filling of a 2D array before using prime numbers, although i think i'm messing up somewhere..
when doing the line int priorNum = arr[r-1][c]; (see full code below) i run into an exception. i am trying to overwrite other lines in my array with this new equation, but must i be stopped by this utmost unchivalrous java error.
the error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 10
my array: int[][] arrayDimension = new int[10][6];
public static void populate2D (int[][] arr) {
//hardcode in values first :)
//and then peek up one row, but you can't go above the original row
arr[0][1] = 10;
arr[0][2] = 100;
arr[0][3] = 500;
arr[0][4] = 1000;
arr[0][5] = 5000;
int count = 0;
//for each row..
for (int r = 0; r < arr.length; r++) { //for each row
for ( int c = 0; c < arr[r].length; c++) { //for each column
arr[r][0] = count;
//never navigate out of bounds
//row 0 is where we're at.. how to populate further rows..?
int priorNum = arr[r-1][c];
int nextNum = priorNum * 2;
arr[r][c] = nextNum;
//can't look back .. SO go UP one.. which is r - 1 goes back one.. and then the length goes - 1
//when c is - peek UP a row < and enter last column.. ^
}
count++;
}
}
i left in some notes that i wrote if you can understand what i'm trying to go for :)
i can also offer this printArray method i wrote for any testing you'd like to try!
public static void print2DArray(int[][] arr) {
for ( int r = 0; r < arr.length; r++) {
for ( int c = 0; c < arr[r].length; c++) {
System.out.print(arr[r][c] + "\t");
}
System.out.println();
}
}
}
thank you for any replies / assistance! everyone here seems very nice, i could not find my type of question that deals with my answer so i felt bad about posting hehe
The problem I can see is that in the first iteration when int priorNum = arr[r-1][c]; gets executed, r = 0, as specified by your outer for loop.
So you are basically trying to access an element of your 2D array using a negative index, which will result in an ArrayIndexOutOfBoundException being thrown.
You could adopt an if statement that will handle the first iteration so that you will not access a prior index.
You could also look at the Array access section of the following article:
https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html
Hope this helped.

Why is the for loop running even though the condition is false

I have been trying to write a code trace for this program. after many attempts on paper I thought I understood it but now I have stumbled again.
In the for loop i=counter ,because i=0 and the counter=0 so since it has to be less than counter how is this code even running?
I have included my incomplete code trace below.
The aim of the program is to print 50 unique random numbers between 1 and 999, in 10 rows of 5. The program works perfectly.I just want to figure out how its working with the help of a code trace. I know this might be a simple problem to you, but I am struggling with it. Could you please help me, thank you.
import java.util.Random;
public class Random50 {
public static void main(String[] args) {
int numbersNeeded = 50;
int[] randomNumbers = new int[numbersNeeded];
int counter = 0;
Random randomGenerator = new Random();
int max = 999;
int min = 1;
while (counter < numbersNeeded) {
int generated = min + randomGenerator.nextInt(max);
boolean found = false;
for (int i = 0; i < counter && !found; i++) {
if (randomNumbers[i] == generated) {
found = true;
}
}
if (!found) {
randomNumbers[counter++] = generated;
}
}
for (int i = 0; i < counter; i++) {
System.out.printf("%03d ",randomNumbers[i] );
if (i > 0 && (i+1) % 5 == 0) {
System.out.println("");
}
}
}
}
This line is the reason why:
randomNumbers[counter++] = generated;
By using counter++, you're using the ++ postfix increment operator, which evaluates to the value of counter, but then increments it by 1 after the evaluation. The equivalent code without use of this operator would look something like this:
randomNumbers[counter] = generated;
counter = counter + 1;
So on the first iteration where this line is executed, randomNumbers[0] is updated, but then counter gets set to 1 (because 0 + 1 = 1). On the second iteration, randomNumbers[1] is updated, then counter gets updated to 2 (because 1 + 1 = 2)...and so forth.
You can find more information about arithmetic operators here: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html

nested for loops integers missing from array

Beginner here. I'm having problems running this series of for loops to find which integers are missing from an array.
public class FunWithArrays{
public static void main(String[] args){
String nString = args[0];
int n = Integer.parseInt(nString);
int inputArray [] = {1,2,4};
System.out.println(" The missing numbers are " );
findMissingNum(n, inputArray);
}
public static void findMissingNum(int n, int[] inputArray){
for (int i = 1; i <= inputArray.length; i++){
int count = 0;
for( int j = 0; j < n; j++){
if(inputArray[j] == i){
count ++;
}
if (count == 0){
System.out.println(i);
}
}
}
}
}
I get the answer I want, namely 3, however it doesn't print but rather shows up in a runtime error:
java.lang.ArrayIndexOutOfBoundsException: 3
at FunWithArrays.findMissingNum(FunWithArrays.java:17)
at FunWithArrays.main(FunWithArrays.java:9)
the method should take an input n from the user (when the program is run) as the largest value of the array and print all the ones missing
The logic is the outer for loop should traverse the array for numbers 1-n, and the inner loop should add to the count variable each time it finds a certain number. At the end of iteration it should print any numbers with a final "count" of 0. THIS IS LITERALLY DRIVING ME CRAZY!!! thanks in advance :)
First of all, you should traverse from 0 to (inputArray.length-1) index of inputArray. This will get rid of the ArrayIndexOutOfBoundsException, because java array indexing starts from 0 not 1.
And for inner loop, run from 0 to n, since n is the max number.
And Thirdly, it should be inputArray[i] == j, not inputArray[j] == i, same for printing the value. In you case I believe you have n>=4, so it was trying to access inputArray[3] via inputArray[j] call. That's why you are getting this out of bound error.
I think your code means like this: nest loop always run through inner loop first before run the outer loop.
public static void findMissingNum(int n, int[] inputArray){
for (int i = 1; i <= n; i++){
int count = 0;
for( int j = 0; j < inputArray.length; j++){
if(inputArray[j] == i){
count ++;
}
if (count == 0){
System.out.println(i);
}
}
}
}
I will just use a while loop instead:
int num =1;
while(num<=n){
for(int i = 0;i<inputArray.length;i++){
if(inputArray[i]!=num){
System.out.println(num);
}
}
num++;
}
The i incrementing to <= ipnutArray.length is not causing the error because i is never used as the index. What is causing the error is when n > length.
Also, you should not be checking n elements starting from the beginning because n is the max value, not the number of elements.

Analysis of execution frequency code

I was trying to find out the frequency of execution of some statements in the following code.
I wanted to check how many times each for loop was executed for a given input array.
For this purpose,I added three variables icnt,jcnt and kcnt.
public class FreqCounter{
public static void count1(int[] a){
int N = a.length;
int count = 0;
int icnt = 0;
int jcnt = 0;
int kcnt = 0;
for(int i=0;i<N;i++){
icnt++;
for(int j=i+1;j<N;j++){
jcnt++;
for(int k=j+1; k<N;k++){
kcnt++;
}
}
}
System.out.printf("i loop=%d times\n",icnt);
System.out.printf("j loop=%d times\n",jcnt);
System.out.printf("k loop=%d times\n",kcnt);
}
public static void main(String[] args) {
int N = 100;
int[] a = new int[N];
count1(a);
}
}
I got the following output
i loop=100 times
j loop=4950 times
k loop=161700 times
I tried to analyze this as follows
The outer for loop (i=0 to < N)
This executes N times ,so for N=100 ,the count will be 100
Inner for loop(j=i+1 to < N)
This is equivalent to finding combinations of N elements ,taken 2 at a time
which means C(N,2) = N! /((N-2)! * 2!) = (N *(N-1))/2 = ((N^2)/2)-(N/2)
For N=100 , this will be (100*100/2)-50 = 4950
Innermost loop (k=j+1 to < N)
Equivalent to finding combinations of N elements ,taken 3 at a time
ie, C(N,3) = N!/((N-3)! * 3!) = N*(N-1)*(N-2)/3! = (N^3/6)-(N^2/2)+N/3
For N=100, this will be 100^3/6 - 100^2/2 + 100/3 = 161700
I am getting the correct values,but wanted to know if the analysis(combinations stuff) is proper.(I have only recently learned the permutation/combinations lessons).If someone can add more to this analysis, it would be helpful.
Your combinatorics is perfectly fine, you have n distinct elements, and you need the number of possibilities to chose 3 elements, order does not matter, no repeats. This is indeed C(N,3).
(Disclaimer, I was a combinatorics TA during the last months)

Adding integers of array upto some number (java)

I have a java question.
I have two int[] arrays: cdn and cmn.
cdn is {1,1,1,1,1,1,2,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
cmn is {8,8,16}
I need a program that adds the consecutive integers of cdn[] upto cmn[init] and returns the number of integers used in the addition. Then it continues adding from the next integer of cdn[] upto cmn[init+1] and return the number of integers. For the arrays above this is done 3 times: the first time the return value is 7, the second time it is 7, and the third time it is 16. The number of integers can be collected in and int[] which is {7,7,16}. The code I have is:
int numofints = 0;
int init = 0;
int plus = 0;
while(init < m2){
for(int j = 0; j < cdn.length; j++){
plus += cdn[j];
numofints++;
if(plus == cmn[init]){
init++;
}
}
}
System.out.print(numofints);
in which m2 is the size of cmn, which is 3 in this case. Note that my program starts to loop from the beginning of cdn over and over again, because j = 0. I want it to start where it ended the previous time!
I hope you have a solution for me.
Bjorn
just pull j out of the outer loop, and use a while, instead of for, for the inner loop
and you also need to put plus = 0 into the loop
public class T {
public static void main(String[] args) {
int[] cdn = {1,1,1,1,1,1,2,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
int[] cmn = {8,8,16};
int numofints = 0;
int init = 0;
int m2 = 3;
int j = 0;
while(init < m2){
int plus = 0;
while(j < cdn.length){
plus += cdn[j];
j++;
numofints++;
if(plus == cmn[init]){
init++;
System.out.println(j);
break;
}
}
if (j == cdn.length) break;
}
}
}
Shoudln't if(plus == cmn[init]){ be if(plus >= cmn[init])? If you change cdn at all and "plus" happens to go over "cmn[init]", your code is going to break.

Categories