exception in thread main java.lang.arrayindexoutofboundsexception 1 - arrays

well i have to make a java program which determinate if a given number is capicua(131,12121,13431) the same number from last to initial digit. but it gives me the error, in the line 23 (while(i>=0).....) the question is how can i call the array into thath while. pls help me im really sad :c. Here is the code:
public class Capi {
/**
*
**/
public static int num(int a) { // counting digits from the number
int n = 0;
while(a>=10) { a = a/10;
n = n+1;
}
return n;
}
public static boolean det(int a, int n) {
int z = a;
double y =0;
n = n-1;
int i = 0;
int x[] = new int[n];
for(i=0; i<x.length; i++) { // saving the digits into x[i]
x[i] = a%10;
a = a/10;
}
while(i>=0) { y = x[i]*Math.pow(10,n-1); // calling the digits x[i],x[i-1] untill it gets 0
i = i - 1;
n = n -1;
}
double num1= y + a*Math.pow(10,n);
if(num1 == z) { return true; }
else { return false; }
}
}

I feel the issue is that the value of i is set to x.length, before you attempt while(i>=0). I have hence added i-- before you run the loop.
See if the following does the trick.
public class Capi {
public static int num(int a) { // counting digits from the number
int n = 0;
while(a>=10) {
a = a/10;
n = n+1;
}
return n;
}
public static boolean det(int a, int n) {
int z = a;
double y = 0;
n = n-1;
int i = 0;
int x[] = new int[n];
for(i=0; i<x.length; i++) { // saving the digits into x[i]
x[i] = a%10;
a = a/10;
}
//i is now set to x.length, thus decrement it as index runs from 0 to x.length-1
i=i-1;
while(i>=0) {
y = x[i]*Math.pow(10,n-1); // calling the digits x[i],x[i-1] untill it gets 0
i = i - 1;
n = n -1;
}
double num1= y + a*Math.pow(10,n);
if(num1 == z) {
return true;
}
else {
return false;
}
}
}

Related

number of subarray with average greater than average of the rest of the elements of array

We are given a array of size < 2000
and A[i]< 10^6.I know the bruteforce approach.Can we do better i.e in linear time ?
I am checking each subarray and comparing its average with the other elements.
public class FindingSubArray {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
ArrayList<Integer> a = new ArrayList<>();
ArrayList<Integer> b = new ArrayList<>();
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
double avg1 = getAverage(i,j,arr);
double avg2 = getAverageOfRest(i,j,arr);
//System.out.println(avg1+" "+avg2);
if(avg1 > avg2) {
a.add(i+1);
b.add(j+1);
}
}
}
System.out.println(a.size());
for(int i=0;i<a.size();i++){
System.out.println(a.get(i)+" "+b.get(i));
}
}
private static double getAverageOfRest(int i, int j, int[] arr) {
double result = 0;
int count = 0;
for(int k=0;k<i;k++) {
result += arr[k] ;
count ++;
}
for(int k=j+1;k<arr.length;k++) {
result += arr[k] ;
count ++;
}
if(count > 0)
return result/count;
else
return 0;
}
private static double getAverage(int i, int j, int[] arr) {
double result = 0;
int count = 0;
for (int k = i; k <= j; k++) {
result += arr[k] ;
count ++;
}
if(count > 0)
return result/count;
else
return 0;
}
}

Code seems to continue running after return statement (in C)

I am trying to create a binary search algorithm and have used two sets of if statements for when the sample is even/uneven. The uneven side currently works as planned and returns true, the even side returns true but then goes to the "catch all" piece of code at the bottom of the function and returns false:
bool search(int value, int values[], int n)
{
//searching algorithm
if (n <= 0)
{
return false;
}
//searching algorithm where n is even, if b is not the searched for value, split the sample and run recursively until value is equal to b or n<=0
if (n % 2 == 0)
{
int starte = n / 2;
eprintf("starte is %i", starte);
int startpluse = starte + 1;
int b = values[starte];
eprintf("b is %i", b);
//for (int i=0; i<n; i++){
//printf("%i,",values[i]);}
if (b == value)
{
printf("true\n");
return true;
}
else
{
if (value > b)
{
int o = starte - 1;
int searcharrayc[o];
for (int h = startpluse, l = 0; l < o; h++, l++)
{
searcharrayc[l] = values[h];
}
search(value, searcharrayc, o);
}
if (value < b)
{
int searcharrayd[starte];
for (int m = 0; m < starte; m++)
{
searcharrayd[m] = values[m];
}
search(value, searcharrayd, starte);
}
}
}
//searching algorithm where n is uneven, if a is not the searched for value, split the sample and run recursively until a is equal to the value or n<=0
if (n % 2 == 1)
{
eprintf("n is %i", n);
int start = (n / 2) - 0.5;
int startplus = start + 1;
int a = values[start];
eprintf("a is %i", a);
if (a == value)
{
return true;
}
else
{
if (value > a)
{
int searcharray[start];
for (int i = startplus, j = 0; j < start; i++, j++)
{
searcharray[j] = values[i];
eprintf("i is %i", i);
}
search(value, searcharray, start);
}
if (value < a)
{
int searcharrayb[start];
for (int k = 0; k < start; k++)
{
searcharrayb[k] = values[k];
eprintf("k is %i", k);
}
search(value, searcharrayb, start);
}
}
}
return false;
}
Your code looks like this:
search(...)
{
if(cond)
return false
if(cond)
return true
else
search(...)
return false
}
You need to change it to:
search(...)
{
if(cond)
return false
if(cond)
return true
else
return search(...)
}
Note the extra return before the recursive call to search

Find pset3 "\expected an exit code of 0, not 1"

all mighty community of CS50ers on StackOverflow!
I have coded the sort and search functions of pset3, find, but I just don't get why I get this message. It is as if in the while loop the first if were never executed.
Any hints?
#include <cs50.h>
bool search(int value, int values[], int n)
{
if (n < 1)
{
return false;
}
else
{
int start = 0, end = (n-1);
while (end >= start)
{
int median = (end - start) / 2;
if (median == value)
{
return true;
}
else if (values[median] < value)
{
start = values[median + 1];
}
else
{
end = values[median - 1];
}
}
return false;
}
}
void sort(int values[], int n)
{
int temp;
for (int i = 0; i < n; i++)
{
int smallest_index = i;
for (int j = i + 1; j < n; j++)
{
if (values[i] > values[j])
smallest_index = j;
}
temp = values[smallest_index];
values[smallest_index] = values[i];
values[i] = temp;
}
}
Click Here to See Error Message from Check50

Sorting an Array of Objects by their Int

So I tried implementing my Quicksort for sorting an array of Edges by their weight which is in int for my Kruskal's algorithm implementation. Is there a built function in javascript for sorting an array of objects by their properties? In this case by their weight. From smallest weight to the largest.
Here is my edge class.
class Edge
{
private int u;
private int v;
private int weight;
public Edge(int i, int i2, int w)
{
u = i;
v = i2;
weight = w;
}
public int getU() {
return u;
}
public int getV() {
return v;
}
public int getWeight() {
return weight;
}
}
Kruskal's code
class MSTKruskal
{
Edge[] mst(int[][] G)
{
Edge A[] = new Edge[G.length - 1];
Forest aForest = new Forest(G.length);
Edge E[] = new Edge[(G.length * G.length - G.length)/2];
int i3 = 0;
for (int i = 0; i < G.length; i++)
{
for(int i2 = i+1; i2 < G.length; i2++)
{
Edge anEdge = new Edge(i, i2, G[i][i2]);
E[i3] = anEdge;
i3++;
}
}
print(E);
//QuickSort(E, 0, E.length);
print(E);
int index = 0;
for (int i = 0; i < E.length; i++)
{
if (aForest.findSet(E[i].getU()) != aForest.findSet(E[i].getV()))
{
A[index] = E[i];
index++;
aForest.union(E[i].getU(), E[i].getV());
}
}
aForest.printA();
return A;
}
In javascript you can pass function as parameter to sort method, this function should take 2 parameters (a and b), and return:
0, if a == b
<0, if a < b
>0, if a > b
In your case it should be something like:
var a=[15,7,100,50];
a.sort(function(a,b){return a.weight-b.weight;});
So you can easily sort by any arrays contents' properties or even more complex criteria.

Pointers and Dynamic Memory

I have a function that returns a pointer to an array. I'm running it in a loop and free() seems to be giving me problems. I'm not sure where, but it appears that somewhere in the main loop the memory that I'm trying to free is being used. I'm using Xcode 3.2.1 in 10.6 | Debug | x86_64 build.
The program will run through the main loop one time; the second time it encounters the free() it gives me the following error:
malloc: *** error for object 0x100100180: incorrect checksum for freed object -
object was probably modified after being freed.
Can someone point out (no pun intended) what I'm doing wrong with pointers here?
Here is the program:
int main(int argc, char **argv) {
int *partition;
int lowerLimit;
int upperLimit;
// snip ... got lowerLimit and upperLimit from console arguments
// this is the 'main loop':
for (int i = lowerLimit; i <= upperLimit; i += 2) {
partition = goldbachPartition(i);
printOutput(partition[0], partition[1], i);
free(partition); // I get problems on the second iteration here
}
return 0;
}
int *goldbachPartition(int x) {
int solved = 0;
int y, z;
int *primes;
int *result;
result = intAlloc(2);
primes = atkinsPrimes(x);
for (int i = intCount(primes)-1; i >= 0; i--) {
y = primes[i];
for (int j = 0; j < y; j++) {
z = primes[j];
if (z + y >= x) {
break;
}
}
if (z + y == x) {
solved = 1;
result[0] = y;
result[1] = z;
break;
} else if (y == z) {
result[0] = 0;
result[1] = 0;
break;
}
}
free(primes);
return result;
}
int *atkinsPrimes(int limit) {
int *primes;
int *initialPrimes;
int *filtered;
int *results;
int counter = 0;
int sqrtLimit;
int xLimit;
int resultsSize;
primes = intAlloc(limit+1);
intFillArray(primes, limit+1, 0);
sqrtLimit = floor(sqrt(limit));
xLimit = floor(sqrt((limit+1) / 2));
// these loops are part of the Atkins Sieve implementation
for (int x = 1; x < xLimit; x++) {
int xx = x*x;
for (int y = 1; y < sqrtLimit; y++) {
int yy = y*y;
int n = 3*xx + yy;
if (n <= limit && n % 12 == 7) {
primes[n] = (primes[n] == 1) ? 0 : 1;
}
n += xx;
if (n <= limit && (n % 12 == 1 || n % 12 == 5)) {
primes[n] = (primes[n] == 1) ? 0 : 1;
}
if (x > y) {
n -= xx + 2*yy;
if (n <= limit && n % 12 == 11) {
primes[n] = (primes[n] == 1) ? 0 : 1;
}
}
}
}
for (int n = 5; n < limit; n++) {
if (primes[n] == 1) {
for (int k = n*n; k < limit; k += n*n) {
primes[k] = 0;
}
}
}
initialPrimes = intAlloc(2);
if (limit >= 2) {
initialPrimes[counter++] = 2;
}
if (limit >= 3) {
initialPrimes[counter++] = 3;
}
filtered = intFilterArrayKeys(primes, limit+1);
results = intMergeArrays(initialPrimes, filtered, counter, trueCount(primes, limit+1));
resultsSize = counter + trueCount(primes, limit+1);
free(primes);
free(initialPrimes);
free(filtered);
results[resultsSize] = 0;
return results;
}
int trueCount(int *subject, int arraySize) {
int count = 0;
for (int i = 0; i < arraySize; i++) {
if (subject[i] == 1) {
count++;
}
}
return count;
}
int intCount(int *subject) {
// warning: expects 0 terminated array.
int count = 0;
while (*subject++ != 0) {
count++;
}
return count;
}
void intFillArray(int *subject, int arraySize, int value) {
for (int i = 0; i < arraySize; i++) {
subject[i] = value;
}
}
int *intFilterArrayKeys(int *subject, int arraySize) {
int *filtered;
int count = 0;
filtered = intAlloc(trueCount(subject, arraySize));
for (int i = 0; i < arraySize; i++) {
if (subject[i] == 1) {
filtered[count++] = i;
}
}
return filtered;
}
int *intMergeArrays(int *subject1, int *subject2, int arraySize1, int arraySize2) {
int *merge;
int count = 0;
merge = intAlloc(arraySize1 + arraySize2);
for (int i = 0; i < arraySize1; i++) {
merge[count++] = subject1[i];
}
for (int i = 0; i < arraySize2; i++) {
merge[count++] = subject2[i];
}
return merge;
}
int *intAlloc(int amount) {
int *ptr;
ptr = (int *)malloc(amount * sizeof(int));
if (ptr == NULL) {
printf("Error: NULL pointer\n");
}
return ptr;
}
void printOutput(int num1, int num2, int rep) {
if (num1 == 0) {
printf("%d: No solution\n", rep);
exit(0);
} else {
printf("%d = %d + %d\n", rep, num1, num2);
}
}
Why is intAlloc not returning int* ?
int *intAlloc(int amount) {
int *ptr;
ptr = (int *)malloc(amount * sizeof(int));
if(ptr == NULL) {
printf("Error: NULL pointer\n");
exit(1);
}
return ptr; //like this
}
EDIT (after your update):
On atkinsPrimes() where is filtered being intAlloc()ed?
int *atkinsPrimes(int limit) {
int *primes;
int *initialPrimes;
int *filtered;
int *results;
int resultsSize;
primes = intAlloc(limit+1);
// ...
initialPrimes = intAlloc(2);
// ...
resultsSize = counter + trueCount(primes, limit+1);
free(primes);
free(initialPrimes);
free(filtered); // Where was it intAlloc()ed?
results[resultsSize] = 0; // make the array 0-terminated to make it easier to work with
return results;
}
EDIT (after your N-th update):
This is a compilable version of your code. It ran smooth on my machine, no crashes. Compiled with g++ (due to declarations of variables inside the for statement):
g++ (Debian 4.3.2-1.1) 4.3.2
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int *goldbachPartition(int x);
int *atkinsPrimes(int limit);
int trueCount(int *subject, int arraySize);
int intCount(int *subject) ;
void intFillArray(int *subject, int arraySize, int value);
int *intFilterArrayKeys(int *subject, int arraySize);
int *intAlloc(int amount);
void printOutput(int num1, int num2, int rep) ;
int *intMergeArrays(int *subject1, int *subject2, int arraySize1, int arraySize2);
int main(int argc, char **argv) {
if (argc < 3) {
printf("Usage: ./program <lower> <upper>\n");
return 0;
}
int *partition;
int lowerLimit = atoi(argv[1]);
int upperLimit = atoi(argv[2]);
// snip ... got lowerLimit and upperLimit from console arguments
// this is the 'main loop':
for (int i = lowerLimit; i <= upperLimit; i += 2) {
partition = goldbachPartition(i);
printOutput(partition[0], partition[1], i);
free(partition); // I get problems on the second iteration here
}
return 0;
}
int *goldbachPartition(int x) {
int solved = 0;
int y, z;
int *primes;
int *result;
result = intAlloc(2);
primes = atkinsPrimes(x);
for (int i = intCount(primes)-1; i >= 0; i--) {
y = primes[i];
for (int j = 0; j < y; j++) {
z = primes[j];
if (z + y >= x) {
break;
}
}
if (z + y == x) {
solved = 1;
result[0] = y;
result[1] = z;
break;
} else if (y == z) {
result[0] = 0;
result[1] = 0;
break;
}
}
free(primes);
return result;
}
int *atkinsPrimes(int limit) {
int *primes;
int *initialPrimes;
int *filtered;
int *results;
int counter = 0;
int sqrtLimit;
int xLimit;
int resultsSize;
primes = intAlloc(limit+1);
intFillArray(primes, limit+1, 0);
sqrtLimit = floor(sqrt(limit));
xLimit = floor(sqrt((limit+1) / 2));
for (int x = 1; x < xLimit; x++) {
int xx = x*x;
for (int y = 1; y < sqrtLimit; y++) {
int yy = y*y;
int n = 3*xx + yy;
if (n <= limit && n % 12 == 7) {
primes[n] = (primes[n] == 1) ? 0 : 1;
}
n += xx;
if (n <= limit && (n % 12 == 1 || n % 12 == 5)) {
primes[n] = (primes[n] == 1) ? 0 : 1;
}
if (x > y) {
n -= xx + 2*yy;
if (n <= limit && n % 12 == 11) {
primes[n] = (primes[n] == 1) ? 0 : 1;
}
}
}
}
for (int n = 5; n < limit; n++) {
if (primes[n] == 1) {
for (int k = n*n; k < limit; k += n*n) {
primes[k] = 0;
}
}
}
initialPrimes = intAlloc(2);
if (limit >= 2) {
initialPrimes[counter++] = 2;
}
if (limit >= 3) {
initialPrimes[counter++] = 3;
}
filtered = intFilterArrayKeys(primes, limit+1);
results = intMergeArrays(initialPrimes, filtered, counter, trueCount(primes, limit+1));
resultsSize = counter + trueCount(primes, limit+1);
free(primes);
free(initialPrimes);
free(filtered);
results[resultsSize] = 0;
return results;
}
int trueCount(int *subject, int arraySize) {
int count = 0;
for (int i = 0; i < arraySize; i++) {
if (subject[i] == 1) {
count++;
}
}
return count;
}
int intCount(int *subject) {
// warning: expects 0 terminated array.
int count = 0;
while (*subject++ != 0) {
count++;
}
return count;
}
void intFillArray(int *subject, int arraySize, int value) {
for (int i = 0; i < arraySize; i++) {
subject[i] = value;
}
}
int *intFilterArrayKeys(int *subject, int arraySize) {
int *filtered;
int count = 0;
filtered = intAlloc(trueCount(subject, arraySize));
for (int i = 0; i < arraySize; i++) {
if (subject[i] == 1) {
filtered[count++] = i;
}
}
return filtered;
}
int *intMergeArrays(int *subject1, int *subject2, int arraySize1, int arraySize2) {
int *merge;
int count = 0;
merge = intAlloc(arraySize1 + arraySize2);
for (int i = 0; i < arraySize1; i++) {
merge[count++] = subject1[i];
}
for (int i = 0; i < arraySize2; i++) {
merge[count++] = subject2[i];
}
return merge;
}
int *intAlloc(int amount) {
int *ptr;
ptr = (int *)malloc(amount * sizeof(int));
if (ptr == NULL) {
printf("Error: NULL pointer\n");
}
return ptr;
}
void printOutput(int num1, int num2, int rep) {
if (num1 == 0) {
printf("%d: No solution\n", rep);
exit(0);
} else {
printf("%d = %d + %d\n", rep, num1, num2);
}
}
Since you are still omitting some source, I can only imagine that the problem is hidden there.
EDIT: (my last update)
To assist your debugging, you should replace your main() function by the one below:
int main(int argc, char **argv)
{
int *primes = NULL;
primes = atkinsPrimes(44); // Evil magic number
free(primes);
return 0;
}
Having a minimal example to reproduce the behavior you pointed out is much better then the whole thing. Have fun with atkinsPrimes(44)

Resources