Prime Numbers Array in Java - java

I want to return an array that displays all the prime numbers within a certain range from 0 till whatever number I enter.
For the range from 0 to 5 I would like the array returned with [2,3,5]. Within the task I was told by my professor that I should fill the whole array with 0 before replacing those 0 wih prime numbers later.
Currently my code does not return the correct array as I do not seem to access the next location in the array but seem to always assign the value to the first location in the array.
My current result array is not [2,3,5] but [5,0,0,0,0].
Any help would be greatly appreciated.
public static int[] generierePrimzahlen(int bis){
int [] myAry = new int[bis];
Arrays.fill(myAry,0);
for(int i=0;i<myAry.length;i++){
for (int nextprime=1; nextprime < bis; nextprime++){
int counter = 0;
// System.out.println(nextprime);
if (istPrimzahl(nextprime)){
myAry[counter] = nextprime;
counter++;
}
}
System.out.print(myAry[i]+" ");
}
return myAry;
}
PS: I have a functioning method (istPrimzahl), which checks if a certain number is a prime number or not.

The problem is that your counter is in the wrong scope.
so instead of incrementing. on every iteration of the first for loop, you declare a new counter. so that it is 0 at the time u assign the prime number to the array.
public static int[] generierePrimzahlen(int bis){
int [] myAry = new int[bis];
// Arrays.fill(myAry,0); // no need, this is already been done at initialization
for(int i=0;i<myAry.length;i++){
int counter = 0;
// adding <= 'nextprime <= bis;' to check also the last number in the range
for (int nextprime=1; nextprime <= bis; nextprime++){
// int counter = 0; wrong scope
// System.out.println(nextprime);
if (istPrimzahl(nextprime)){
myAry[counter] = nextprime;
counter++;
}
}
if(myAry[0] != 0) // to get rid of displaying Zeros
System.out.print(myAry[i]+" ");
}
return myAry;
}

Put below line outside both for loop. That will work.
Reason for issue is - you are resetting the counter while entering the for loop.
int counter = 0;

ArrayList will be a better choice than array. However if using array is another school requirement, then what you have done:
int[] myAry = new int[size];
will already set all elements to zeroes.
There is also no need to use 2 loops for this. Just:
Loop through from 1 to n
if current number is prime, set it to array of current index
idx++
I do not seem to access the next location in the array but seem to always assign the value to the first location in the array.
That is because you are setting your counter variable back to zero in every iteration. You should declare it outside your loop.
Example:
int idx = 0; //place this outside the loop
for(int i=1; i<=n; i++)
if(isPrime(i))
myAry[idx++] = i;

Related

Facing problem with the output of this code

My friend gave me this code and i cant seem to find the error in it. I am attaching the code below:
import java.util.*;
public class prg {
public static void main(String[] args) {
int n;
int count;
int a=0,b=1;
int c=0;
Scanner kb=new Scanner(System.in);
n=kb.nextInt();
int ar[]=new int[100];
ar[1] = 2;
for(int i=3;i<=n;i+=2)
{
count=0;
for (int j = 2; j < i ;j++ ) {
if (i % j == 0) {
count++;
break;
}
}
if(count==0)
ar[i]=i;
}
for(int i=0;i<=n;i+=2)
{
a = b;
b = c;
c = a + b;
ar[i]=c;
}
for(int i=0;i<14;i++)
System.out.print(ar[i]+" ");
}
}
So, the even index is storing the fibonacci series and the odd index is storing prime number.
Problem: the rest of the code is working fine but the 9th index of 'ar' array is printing 0 i dont know why and because of it the output is showing wrong.
Take input n as 14 and check the code please.
Thankyou in advance.
PS: i have solved this question in one other way so i request you to not give answers like 'try my method, its not efficient'. I just want to know what is going wrong at INDEX 9 of the array.
Edited: facing problem with the Prime Number loop.
When i is 9, your code correctly identifies that it is not a prime number, so count is not 0. This causes this line to not run:
ar[i]=i;
And then you increase i by 2 to check the next odd number. This means that you never set index 9 of the array to anything, so it remains at its default value - 0.
To fix this, you should introduce a new variable possiblePrime to keep track of which number you are checking. Increase this variable every iteration of the outer for loop, and increase i only when possiblePRime is prime. Also, change the above line to:
ar[i] = possiblePrime;
9 is not a prime number, so it sets nothing in the array. 0 is the default value so it gets printed.

finding the number of pairs of numbers in an array that add up to a number

I am trying to come up with a program that will search inside of an array that is given a length by the user that picks out whether there is a pair of numbers that sum to 7. The idea is that if there is k amount of dice being thrown, how many pairs of numbers out of those dice thrown add up to 7. So far this is all that I could come up with but I am very stuck.
This is the driver class for the program. I have to write a class that will make this driver function properly.
import java.util.Scanner;
public class SevenDriver{
public static void main(String[] args){
System.out.println("Enter number of dice to toss");
Scanner s = new Scanner(System.in);
int diceCount = s.nextInt();
SevenTally t = new SevenTally(diceCount);
int experiments = 1000000;
int wins = 0;
for(int j = 0; j < experiments; j++)
if(t.experiment()) wins++;
System.out.println((double)wins/experiments);
}
}
This is what I have so far. It does not currently work or compile. I am just looking for some ideas to get me going. Thanks!
public class SevenTally{
private int diceCount;
public SevenTally(int die){
diceCount = die;
}
public int genDice(){
return 1 + (int)(Math.random()*6);
}
public boolean experiment(){
boolean[] nums = new boolean[diceCount];
int ranNum;
int sum = 7;
for(int i = 0; i < nums.length; i++){
ranNum = genDice();
if (nums[ranNum] == sum){
return true;
}
}
int left = 0;
int right = nums.length - 1;
while(left<right){
int tempSum = nums[left] + nums[right];
if(tempSum == 7){
return true;
}
else if(tempSum>7){
right--;
}
return false;
}
}
First populate your array of length k with random int in [1;6]
The number of possible pairs in an array of length k is the number of 2-combinations in the array, which is (k-1)*k/2 (http://en.wikipedia.org/wiki/Combination)
You can test all the possible pairs (i,j) in your array like so:
int win = 0;
int tally = 7;
for(int i=0; i<k-1; i++){
for(int j=i+1; j<k; j++){
if(array[i]+array[j] == tally){
win++;
}
}
}
What this does is that it sets the first element of the pair to be the first element of the array, and sums it with the other elements one after the other.
It pairs array[0] with array[1] to array[k-1] at the first pass of the i for loop, that's k pairs.
Then k-1 pairs at second pass, and so on.
You end up with (k)+(k-1)+(k-2)+...+1 pairs, and that's exactly (k-1)*k/2 pairs.
done =]
edit: sorry, haven't read the whole thing. the method experiment() is supposed to return a boolean. you can return win>0?true:false; for example...
This Wiki page has some algorithms to do that. Its not a trivial problem...
You're generating a random number in ranNum, and then using it as an index into the array nums. Meanwhile, nums never gets filled, so no matter which box you index into, it never contains a 7.
What you want to do, if I understand your problem correctly, is fill each space in the array with the result of a die roll, then compare every two positions (rolls) to see if they sum to seven. You can do that using a nested for loop.
Essentially, you want to do this: (written in pseudocode as I'm not a java programmer)
int[] results[numrolls]
for (count = 0 to numrolls-1) { results[numrolls]=dieRoller() }
for (outer = 0 to numrolls-2)
for (inner = outer+1 to numrolls-1)
if (results[outer] + results[inner] == 7) return true
return false;
However, in this case there's an even easier way. You know that the only ways to get a sum of 7 on 2d6 are (1,6),(2,5),(3,4),(4,3),(5,2),(6,1). Set up a 6-length boolean array, roll your dice, and after each roll set res[result] to true. Then return (1-based array used for simplicity) ( (res[1] && res[6]) || (res[2] && res[5]) || (res[3] && res[4]) ).
ArrayIndexOutOfBoundsException means you are trying to access an element of the array that hasn't been allocated.
In your code, you create a new array d of length diceCount, but then you genDice() on always 6 elements.

Print an array in java without empty spaces

I am writing a piece of code where someone types in numbers that are added to an array. They can type in a negative number to stop.
int loop1 = 0;
int[] array1;
array1 = new int[10000];
boolean escape = false;
int count = 0;
while (escape == false){
loop1 = scan.nextInt();
count ++;
if (loop1 >= 0){
array1[count] = loop1;
}else{
escape = true;
}
}
There are exactly 10000 spaces in the primitive array. How could I print out the array without the empty spaces
for( int a:array1){
if(a>=0){
System.out.println(a);
}
}
When you initialize the array, all index values set to 0, and you would 0 check.
As a different approach, you could use ArrayList to insert values, which will save you from creating un wanted large array.
Like this:
for(int printCounter = 0; printCounter <= count; printCounter++) {
System.out.println(array1[printCounter]);
}
I guess you should print every number until you hit the negative one :)
Assuming that negative number is stored in the array too

ArrayIndexOutOfBoundsException when looping

I'm pretty much a noob to programming but i have researched all over the place and cant find an answer. im using eclipse and every time i run my program it says:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at computer.guess(game1player2.java:24)
at game1player2.main(game1player2.java:39)
Here's my code:
import java.util.Scanner;
class computer{
int g = 0;
int[] compguess = new int[g];
void guess(){
int rand;
while(0 < 1){
int i;
rand = (int) Math.ceil(Math.random()*10);
for (i = 1; i < compguess.length; i++){
if(rand == compguess[i]){
break;
}
}
if(i > compguess.length){
g++;
rand = compguess[g];
System.out.println(compguess[compguess.length]);
}
}
}
}
public class game1player2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
computer computer1 = new computer();
for(int a = 0; a < 2; a++){
computer1.guess();
for(int n = 0; n <= computer1.compguess.length; n++)
System.out.println(computer1.compguess[n]);
}
{
input.close();
}
}
}
i am now really confused, i am trying to make a computer generate a random number 1-10, but if it is already in the array generates another one.
int g = 0;
int[] compguess = new int[g];
Your array is size 0, so you have no valid entries.
Since you initialized g as zero, your array compguess has a length of zero. Next when you enter your for loop you assign 1 to i which will allow you to enter into the if condition at the end of guess which will try to access element compguess[1] but this cannot exist because the array is of size zero.
You will run into problems if you do not correct the following.
Change: for(int n = 0; n <= computer1.compguess.length; n++)
To: for(int n = 0; n < computer1.compguess.length; n++)
If your array length is 8 then the last item in the array will be index 7, but the <= tells the loop to grab item index 8.
Your compguess has a length of 0, and you are starting your for loop with i = 1, wich is already greater than 0.
compguess is a zero-length array. If you try to index it, you will fall out of the array and hence the ArrayIndexOutOfBoundsException
If your intent is to make the array longer and add a new item to the end of it, you can't do that. I'm guessing that this is what you were trying to do here:
rand = compguess[g];
First of all, if the language did allow it, you'd want to write it the other way:
compguess[g] = rand;
because you're trying to put a value into a new element of the array, not read from the array. This would actually work in some languages (JavaScript, Perl, others). In Java, however, when you create an array object with something like new int[], the size is fixed. You can't make it longer or shorter.
You probably want to use an ArrayList, which does let you create an array that you can make longer. See this tutorial.

Method for avoiding duplicates when generating a random list of pairs of numbers is not working as it should

I have this code for setting random values to true in a boolean[][], without making any duplicates:
int a = 0;
int b = 0;
int counter = 0;
for (int i=0; i<=50; i++) {
do {
a = randomizer.nextInt(hoogte);
b = randomizer.nextInt(breedte);
/**debug variable*/
counter++;
} while (bommaker[a][b]);
bommaker[a][b] = true;
}
After testing for a while, I noticed something was wrong, so I added a counter to check it. Every time I run the program, there comes a different number out of "counter". One time it was 57 while the other time even 63. But I have set the loop to exactly 51. This means the code isn't working as it should. Can somebody explain why it generates more than 51 numbers, and give a possible solution?
You have to remember that you have a loop within a loop. The OUTTER loop is limited to 51 executions, but the inner loop will cause a random number of iterations (an extra iteration for each time it sees that the array has already been set to true).
Other than the counter value being greater than you expected, what about the code is not working?
move out the counter++ line from do while loop
int a = 0;
int b = 0;
int counter = 0;
for (int i=0; i<=50; i++) {
do {
a = randomizer.nextInt(hoogte);
b = randomizer.nextInt(breedte);
/**debug variable*/
} while (bommaker[a][b]);
counter++;
bommaker[a][b] = true;
}

Categories