Sieve of Eratosthenes, ArrayIndexOutOfBoundsException, output is composite number - java

I tried writing a Sieve of Eratosthenes algorithm, I am getting an ArrayIndexOutOfBoundsException but I don't seem to understand why, if I change the limits, upon printing it only displays composite numbers, the code's below help if you can.
public static Boolean[] solution(int N) {
Boolean[] isPrime = new Boolean[N];
isPrime[0] = false;
for(int i = 1; i <= N; i++) {
isPrime[i] = true;
}
for(int i = 2; i <= N; i++) {
if(isPrime[i]== true) {
System.out.println(i);
for(int j = 2; (j * i) < N; j++) {
int k = j * i;
isPrime[k] = false;
}
}
}
return isPrime;

i <= N; cause the error
for(int i = 1; i <= N; i++) {
isPrime[i] = true;
}
for example
if N=4 then you get error when i=4. isPrime[4] cause OutOfBounds exception because length is 4.arrays are zero index based. so maximum index you can access is 3.isPrime[3]
you can avoid this error by changing loop to for(int i = 1; i < N; i++) {
however i'm not sure what is Eratosthenes algorithem is .i hope you can change your code keep in mind arrays are zero index based

Boolean[N] creates an array of N elements, so, since the indexes start from 0, the last index is N-1.
The error is caused by i<=N in the for loop

Related

Leetcode Move Zeroes: where are my bugs?

This is a easy question. a link
I just tried the simple insertionSorting-like method to solve it, however it failed.
public class Solution {
public void moveZeroes(int[] nums) {
for(int i = 0; i < nums.length; i++)
if(nums[i] == 0){
for(int j = i; j<nums.length-1; j++)
nums[j] = nums[j+1];
nums[nums.length-1] = 0;
}
}
}
Could anyone help me to debug my method?
So i went through your code and re-wrote it to work. If you're moving zeroes to the end this should work perfectly fine for you. Cheers.
What this code does is iterates over your array until it hits a zero. Upon hitting a zero it loops, moving the 0 one place to the right over and over, switching spots with the value to the right of it, until the 0 is moved to the end of the array.
example: 5-loop cycle
[0,1,0,2,3] > [1,0,0,2,3] > [1,0,0,2,3] > [1,0,2,0,3] > [1,0,2,3,0]
int[] array = new int[] {0,1,0,12,3};
for (int x = 0; x < array.length; x++) {
if (array[x] == 0) {
for (int y = x; y < array.length; y++) {
if (y != array.length-1) {
// Store our replacement as temp
int temp = array[y+1];
// Move 0 to the right +1
array[y+1] = array[y];
// Set current position to what used to be right+1
array[y] = temp;
}
}
}
}
I'll share the javascript solution for the Move Zeroes problem from leetcode. It has O(n) time complexity.
Optimized for many zeroes
const snowball1 = nums => {
let i = 0;
let j = 0;
while (i<nums.length) {
if(nums[i] != 0) {
nums[j] = nums[i];
j++;
}
i++;
}
console.log(j);
nums.fill(0, j);
return nums;
}
Optimized for fewer zeroes
const snowball2 = nums => {
for(let i = nums.length; i--;){
if(nums[i]===0){
nums.splice(i,1)
nums.push(0);
}
}
return nums
}
Example
console.log(snowball1([0,0,1,0,0,3,0,12,0]));
console.log(snowball2([0,1,0,3,12]));
I'll try to write a very intuitive and easy approach to this problem. This problem can be solved using 2 indexes, one of which is the read pointer(rp) and the other is the write pointer(wp).
If rp reads a value of 0, it sets the wp to this index. The rp then keeps incrementing until it finds a non-zero value. If it does it overwrites the value at wp and this process fills the non-zero values in the beginning.
We then just need to fill the remaining spots with zeros till the end. Here's a short solution in python:
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
wp=rp=0
while(rp<len(nums)):
if(nums[rp]!=0):
nums[wp]=nums[rp]
wp+=1
rp+=1
for i in range(wp,len(nums)):
nums[i]=0
Please find the optimal solution wrt space O(N) and time O(1) below
public void moveZeroes(int[] nums) {
// [0,1,0,3,12]
int j = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
j++;
}
}
}

I can't find the bug in my java method that returns an array of prime numbers.

It only uses the prime numbers to check if the other numbers are also prime
static public int[] primeGen(int a){
int[] series={2};
if (a==1 || a==2 || a<=0){
return series;
}
this is where the errors occur
else{
boolean Prime = false;
for (int i = 3; i<=a; i++){
boolean[] state = {};
for (int j = 0; !(state[state.length-1]) && (j<series.length); j++){
state = Arrays.copyOf(state, state.length +1);
state[state.length -1] = i % series[j] ==0;
}
for (int k = 0; (Prime) && (k<state.length); k++){
Prime = !(state[k]);
}
if (Prime){
series = Arrays.copyOf(series, series.length +1);
series[series.length -1] = i;
}
}
return series;
}
}
Sorry if I just made a rookie mistake, cause I've been learning Java for 3 days now
Your state array is initialized to an empty array, so !(state[state.length-1]) attempts to access an invalid index of the array (-1).
This line
for (int k = 0; (Prime) && (k<state.length); k++){
means that the loop will only be executed if Prime is true. However you have initialized Prime to false and only set it true inside the loop.
It looks like you are using Arrays.copyOf to increase the size of your output array. You can just use Vector.add() instead and the JVM will take care of any resizing needed.
Now it's working fine!
My mistake was that I didn't know that the for loop doesn't start at all if the statement in the middle for(int j =0; (Prime)&&(j<); j++){} is't true. What I thought was that this would be checked only at the end of each repetition. Anyway, I wouldn't have realized this without u guys pointing out that the statements don't add up, so thanks a lot!
boolean Prime = false;
for (int i = 3; i<=a; i++){
boolean[] state = {};
for (int j = 0; (j<series.length); j++){
state = Arrays.copyOf(state, state.length +1);
state[state.length -1] = i % series[j] == 0;
//This is where I added my statement that breaks the loop
if (!(state[state.length-1]==false&&j<series.length)){break;}
}
for (int k = 0; (k<state.length); k++){
Prime = !(state[k]);
//As well as here
if (!(Prime==true&&k<state.length)){break;}
}
if (Prime == true){
series = Arrays.copyOf(series, series.length +1);
series[series.length -1] = i;
}
}
return series;
}
}

ArrayIndexOutOfBounds Exception for some input values

The following is a part of my code.
For some values of bands and bandRows the code seems to run perfectly alright. But for some it gives an ArrayIndexOutOfBounds exception.
Any ideas where I might have gone wrong? I cannot find any mistake in the code.
Thanks in advance
for(int i=0; i<bands; i++)
{
int a=0;
while(a<bucketSize)
{
bandBuckets[i][a] = new ArrayList();
a++;
}
}
for (int i = 0; i < bands; i++)
{
for (int j = 0; j < preprocessedList.size(); j++)
{
int[][] forBuckets = new int[bands][bandRows];
for (int k = 0; k < bandRows; k++)
{
Arrays.fill(forBuckets[i], Bands[i][k][j]);
}
bandBuckets[i][h.hashBands(forBuckets[i], bucketSize)].add(j);
}
}
Here's the h.hashBands() function which is in another class
public int hashBands(int[] in, int bucketSize)
{
int hashVal = 0;
int k = in.length;
int base = 3;
for (int i = 0; i < in.length; i++) {
// for (int j = 0; i < in[i].length; i++)
hashVal += in[i] * Math.pow(base, k - i - 1);
}
return hashVal % bucketSize;
}
Perhaps there is an overflow in your hashBands() function.
The max value for an int is 231 - 1. hashVal will overflow when k - i - 1 is greater than 19. In Java, exceptions aren't thrown for overflows and underflows. Consider using a BigInteger and its modPow() function.
Can you tell where exactly you are getting ArrayIndexOutOfBoundException.
Seeing your code it seems that there might be some problem while returning from hashBands() function. It might be returning something greater than expected.
bandBuckets[i][h.hashBands(forBuckets[i], bucketSize)]
For the 2nd dimension of this array h.hashBands(forBuckets[i], bucketSize) --> this value might be greater than the expected value for that part.....

How to stop a "ArrayIndexOutOfBounds" exception

Hi guys I've been learning java over the summer and this is the last assignment, and I'm stuck. The program is supposed to take 13 numbers that I enter, sort them and then find the index number of the greatest number that I input in the original array. I'm trying to see if my selection method works but every time I try to enter in the numbers I get an out of bounds error. This is kind of frustrating and I've been trying to find and answer for a couple of hours now. Any help would be greatly appreciated. Thanks!
import java.util.Scanner;
public class fmax
{
public static void main(String[] args)
{
int indmax;
int[] fmax = new int[13];
fillmax(fmax);
//System.out.println(fmax);
indmax = maxfmax(fmax);
//indmin = minfmax();
System.out.println(indmax);
}
public static void fillmax(int[] farray)
{
Scanner sc = new Scanner(System.in);
int i = 0;
for(i = 0; i < farray.length; i++)
{
farray[i] = sc.nextInt();
}
}
public static int maxfmax(int[] farray)
{
int[] copy = farray;
int j, x=0, i;
boolean flag = true;
int temp;
while(flag)
{
flag = false;
for( j = 0; j < copy.length -1; j++)
{
if(copy[j] < copy[j+1])
{
temp = copy[j];
copy[j] = copy[j+1];
copy[j+1] = temp;
flag = true;
}
}
for(i=0; i <= farray.length; i++)
{
if(farray[i] == copy[1])
x = i;
}
}
return x;
}
}
This line will throw the out of bounds exception.
for(i=0; i <= farray.length; i++)
Your termination condition is incorrect. Try this:
for(i=0; i < farray.length; i++)
so that you stop the loop before you go past the last index (farray.length - 1).
You defined the Lenght of the Array as 13 than you run this line:
for(i=0; i <= farray.length; i++)
This means you will go for the items fmax[13] which doesnt exist, because java starts counting at 0. So the hightest index is fmax[12]. You need to change your condition to something like that:
for(i=0; i < farray.length; i++)
or
for(i=0; i <= farray.length -1; i++)
In this case length for array is returning size of your array - but it starts with 1 not with zero.
i <= farray.length - causes out of bounds exception
u have to use - as was mentioned i < farray.length in your for loop
Array always has index beginning with zero and ending with length-1
for(i=0; i <= farray.length; i++)
Your terminating condition is wrong. It is trying to access element located at index length, which does not exist and hence you get the exception. It should be modified to something like below to make it work:
for(i=0; i < farray.length; i++)

finding time and space complexity of the given java code

hi i need to find the time and space complexity of the program, pls help, if possible please suggest the optimization that can be performed,
.........................................................................................................................................................................................
public class Sol {
public int findMaxRectangleArea(int [][] as) {
if(as.length == 0)
return 0;
int[][] auxillary = new int[as.length][as[0].length];
for(int i = 0; i < as.length; ++i) {
for(int j = 0; j < as[i].length; ++j) {
auxillary[i][j] = Character.getNumericValue(as[i][j]);
}
}
for(int i = 1; i < auxillary.length; ++i) {
for(int j = 0; j < auxillary[i].length; ++j) {
if(auxillary[i][j] == 1)
auxillary[i][j] = auxillary[i-1][j] + 1;
}
}
int max = 0;
for(int i = 0; i < auxillary.length; ++i) {
max = Math.max(max, largestRectangleArea(auxillary[i]));
}
return max;
}
private int largestRectangleArea(int[] height) {
Stack<Integer> stack =
new Stack<Integer>();
int max = 0;
int i = 0;
while(i < height.length) {
if(stack.isEmpty() ||
height[i] >= stack.peek()) {
stack.push(height[i]);
i++;
}
else {
int count = 0;
while(!stack.isEmpty() &&
stack.peek() > height[i]) {
count++;
int top = stack.pop();
max = Math.max(max, top * count);
}
for(int j = 0; j < count + 1; ++j) {
stack.push(height[i]);
}
i++;
}
}
int count = 0;
while(!stack.isEmpty()) {
count++;
max = Math.max(max, stack.pop() * count);
}
return max;
}
thank you in advance
To find the space complexity take a look at the variables you declare and are larger than a single primitive variable. In fact I believe your space complexity will be determined my the array auxilary and the Stack stack. The size of the first one is pretty clear and I don't completely understand the second one but I see it's size will never be greater than the one of the array. So I would say the space complexity is O(size of(auxilary)) or O(N * M) where N=as.length() and M = as[0].length.
Now the time complexity is a bit trickier. You have two cycles over the whole auxilary array so for sure time complexity is at least O( N * M). You also have another cycle that invokes largestRectangleArea for each row of auxilary. If I get the code in this function correctly it seems this function is again linear, but I am not sure here. Since you know the logic better probably you will be able to compute its complexity better.
Hope this helps.

Categories