How do I see if the first 2, 3, 4 or all numbers are part of another array?Here "lottery" generates 10 numbers 1-100 and "numbers" is getting user's input 5 times.The program compares user's 5 numbers to numbers 1-5 of lottery , 2-6 and so on.Im trying to see if the user guessed a sequence in the lottery array but I cant get it to print out "You guessed 2 nrs" if the user guessed 2 ,3 ,4 or all numbers one after another.I incremented a counter and also tried switch statements but doesn't work.
// to check if user guessed a sequence
int counter=0;
for (int i = 0; i < lottery.length - 5; i++) { // 1-5
for (int j = 0; j < numbers.length; j++) {
if (lottery[i] == numbers[j]) {
counter++;
}
}
}
for (int i = 1; i < lottery.length - 4 ; i++) { // 2-6
for (int j = 0; j < numbers.length; j++) {
if (lottery[i] == numbers[j]) {
counter++;
}
}
}
for (int i = 2; i < lottery.length - 3 ; i++) { // 3 -7 numbers of lottery array
for (int j = 0; j < numbers.length; j++) {
if (lottery[i] == numbers[j]) {
counter++;
}
}
}
for (int i = 3; i < lottery.length - 2; i++) { // 4 - 8 numbers of lottery array
for (int j = 0; j < numbers.length; j++) {
if (lottery[i] == numbers[j]) {
counter++;
}
}
}
for (int i = 4; i < lottery.length - 1; i++) { // 5 -9 numbers of lottery array
for (int j = 0; j < numbers.length; j++) {
if (lottery[i] == numbers[j]) {
counter++;
}
}
}
for (int i = 5; i < lottery.length ; i++) { // 6 -10 numbers of lottery array
for (int j = 0; j < numbers.length; j++) {
if (lottery[i] == numbers[j]) {
counter++;
}
}
}
for (int i = 0; i < numbers.length && i < 2; i++) { // 2 sequence
counter = numbers[i];
}
for (int i = 0; i < numbers.length && i < 3; i++) { // 3 sequence
counter= numbers[i];
}
for (int i =0; i < numbers.length && i < 4; i++) { // 4 sequence
counter = numbers[i];
}
for (int i = 0; i < numbers.length; i++) { // 5 sequence
counter = numbers[i];
}
switch (counter) {
case 1:
System.out.println("You guessed one sequence");
break;
case 2:
System.out.println("You guessed two sequences");
break;
case 3:
System.out.println("You guessed three sequences");
break;
case 4:
System.out.println("You guessed four sequences");
break;
}
Your code is a little bit confusing, most likely because you are not using functions, for what you want to achieve there is a nice code here, lets take a look at it:
static boolean isSubArray(int A[], int B[], int n, int m)
{
// Two pointers to traverse the arrays
int i = 0, j = 0;
// Traverse both arrays simultaneously
while (i < n && j < m)
{
// If element matches
// increment both pointers
if (A[i] == B[j])
{
i++;
j++;
// If array B is completely
// traversed
if (j == m)
return true;
}
// If not,
// increment i and reset j
else
{
i = i - j + 1;
j = 0;
}
}
return false;
}
Now you have a function that will return true if whole sequence A is in sequence B, but that is not the whole code you seem to want. You need to split guessed sequence, what if there is subsequence that fits?
Example (how many are guessed in following?):
int lottery[] = {1,2,3,4,5,6,7,8,9,10};
int A[] = {1,2,3,4,5}; //here we got full match
int B[] = {1,2,4,5,6}; //last three make it 3
int C[] = {1,2,3,7,9}; //first three make it 3
int D[] = {1,3,4,5,9}; //and here is it in the middle!
So what now? You need to check for each lengths, higher lengths first of course, a simple solution can be as follows (check how to create a subarray):
import java.util.Arrays;
public static<T> T[] subArray(T[] array, int beg, int end) {
return Arrays.copyOfRange(array, beg, end + 1);
}
public static boolean checkAll(int A[], int B[], int n, int m, int subset){
for(int i=0;i+subset<n;i++){ //i+subset must be within range
//checking the current subset, iterate them all
if(isSubArray(subArray(A,i,i+subset), B, n, m)){
return true; //if it is there return true!
}
}
return false; //no luck!
}
int lottery[] = {1,2,3,4,5,6,7,8,9,10};
int D[] = {1,3,4,5,9};
counter = 0;
for(counter=D.length; counter>0; counter--){
if(checkAll(D, lottery, D.length, lottery.length, counter)){
break; //we found match, can end
}
}
System.out.println("You guessed sequence of length: %d ", counter);
I guess I have a little bit misunderstood what you are trying to achieve, so same approach for sequences of the lottery:
//subset is probably 5 for lottery
public static int checkAll(int A[], int B[], int n, int m, int subset_A , int subset_B){
int total = 0;//we return this
for(int i=0;i+subset_B<m;i++){ //each subset in lottery
for(int j=0;j+subset_A<n;j++){ //each subset in guesses
if(isSubArray(subArray(A,j,j+subset),subArray(B,i,i+subset), n, m)){
total++;
}
}
return total;
}
int occurences = 0;
for(int counter=lottery.length; counter>0; counter--){
occurences+=checkAll(D, lottery, D.length, lottery.length, counter, 5);
}
System.out.println("Your guessed sequence (and its parts) was present %d times", occurences );
I am still not sure what exactly you want to do, so this code might be a little bit overkill. The code was not tested, some syntax errors might come in the way.
My goal is to create an adjacency matrix generator (the only value elements can have is 0 or 1; it has to be symmetric, meaning element in [i][j] == element [j][i]) in Java.
I have some code, but the result is an nx5 matrix (if I establish n = 13, the resulting matrix is a 13x5 matrix). It is symmetric and the values of elements is bounded between 0-1, so that is not an issue. Another problem is I don't really know how to have an array without doubles, which is more of an aesthetical problem + ideally, the diagonal would be filled with "-" instead of zeroes, as it is now.
Random random = new Random();
double[][] array = new double[n][n];
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j <= i; j++)
{
int x = random.nextInt(2);
array[i][j] = x;
if (i != j)
{
array[j][i] = x;
}
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (i == j || (i + j + 1) == n)
{
array[i][j] = 0;
}
}
}
for (double[] a : array)
{
System.out.println(Arrays.toString(a));
}
}
I'm doing this program: Given an integer, n, if the sum of its divisors (not counting itself) equals n, that number is said to be perfect. If the sum is lower, it is said to be decient, and if it is higher it is said to be abundant. For example:
6 has divisors 1,2,3: they add 6, therefore 6 is perfect. 8 has divisors 1,2,4: they add 7, therefore 8 is deciente. 24 has divisors 1,2,3,4,6,8,12: they add 36, therefore 24 is abundant.
Write a program that reads two positive integers and displays, on the screen, how many numbers there are of each type in that interval (including the extremes).
I have the following code and I know where it fails, for example if I enter a single number, I do it well, example of entries 6 and 7. If I then enter 6 and 9 the output is Perfect 1 Deficient 0 Abundant 2, when I should to be Perfect 1 Deficient 2 Abundant 0. Variable j stores the divisors of all in the variable j and then that's why it's abundant but I have not been able to correct it for more than I've tried.
import java.util.Scanner;
public class PerfectNumbers {
public static void main(String[] args) {
System.out.println("Enter two numbers for the interval:");
Scanner teclado = new Scanner(System.in);
int x = teclado.nextInt();
int y = teclado.nextInt();
int cont1 = 0;
int perfect = 0;
int deficient = 0;
int abundant = 0;
for (int i = x; i < y; i++) {
for (int j = 1; j < i; j++) {
if (i % j == 0) {
cont1 += j;
} else {
cont1 += 0;
}
}
if (cont1 == x) {
perfect += 1;
} else if (cont1 < x) {
deficient += 1;
} else if (cont1 > x) {
abundant += 1;
}
}
System.out.println("Perfect"+ perfect);
System.out.println("Deficient"+ deficient);
System.out.println("Abundant"+ abundant);
}
}
One problem is that you didn't reset cont1.
Another problem is that instead of comparing to x to decide perfect/deficient/abundant, you need to compare to i.
for (int i = x; i < y; i++) {
cont1 = 0;
for (int j = 1; j < i; j++) {
if (i % j == 0) {
cont1 += j;
}
}
if (cont1 == i) {
perfect += 1;
} else if (cont1 < i) {
deficient += 1;
} else {
abundant += 1;
}
}
I think the second problem was easy to overlook because of the poor naming of variables. I suggest to improve that, and it will be easier to read and harder to make such mistakes:
for (int n = start; n < end; n++) {
sum = 0;
for (int j = 1; j < n; j++) {
if (n % j == 0) {
sum += j;
}
}
if (sum == n) {
perfect++;
} else if (sum < n) {
deficient++;
} else {
abundant++;
}
}
I tried it several times but still gives me ArrayOutOfIndex. But i want to save the memory so i use
boolean[]isPrime = new boolean [N/2+1];
instead of
boolean[]isPrime = new boolean [N+1];
This gives me ArrayOutOfIndex for line 23 and 47
line 23:
for (int i = 3; i <= N; i=i+2) {
isPrime[i] = true;
}
line 47:
for (int i = 3; i <= N; i=i+2) {
if (isPrime[i]) primes++;
...
}
Full code:
public class PrimeSieve {
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java PrimeSieve N [-s(ilent)]");
System.exit(0);
}
int N = Integer.parseInt(args[0]);
// initially assume all odd integers are prime
boolean[]isPrime = new boolean [N/2+1];
isPrime[2] = true;
for (int i = 3; i <= N; i=i+2) {
isPrime[i] = true;
}
int tripCount = 0;
// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 3; i * i <= N; i=i+2) {
// if i is prime, then mark multiples of i as nonprime
if (isPrime[i]) {
int j = i * i;
while (j <= N){
tripCount++;
isPrime[j] = false;
j = j + 2*i;
}
}
}
System.out.println("Number of times in the inner loop: " + tripCount);
// count and display primes
int primes = 0;
if(N >= 2 ){
primes = 1;
}
for (int i = 3; i <= N; i=i+2) {
if (isPrime[i]) primes++;
if (args.length == 2 && args[1].equals("-s"))
; // do nothing
else
System.out.print(i + " ");
}
System.out.println("The number of primes <= " + N + " is " + primes);
}
}
You should store and access the array using the same indexing function: isPrime[i/2]
When you change the size of your array from [N+1] to [N/2+1], you need to also update the end-conditions of your for-loops. Right now your for-loops run until i=N, so you are trying to do isPrime[i] when i > (N/2+1) ... so you get an ArrayIndexOutOfBoundsException.
Change this:
for (int i = 3; i <= N; i=i+2)
to this:
for (int i = 3; i <= N/2; i=i+2)
Well, for example if N=50 your isPrime only holds 26 elements, and you're trying to access the elements at 3,5..47,49 (which, of course, is out of bounds)
What you probably want is to use i/2 (as the index) inside your loops, that way you are still iterating over the numbers 3,5..47,49, but you use the correct indexes of your vector.
I have the following code which spits out prime numbers between 1 and N. A friend came up with this solution but I believe there is a more efficient way to write this code. Such as making it so that if (i%j!=0) {System.out.print (i + " ");}. However I found this spat out numbers randomly all over the place...
import java.util.Scanner;
public class AllPrime {
public static void main(String[] args) {
System.out.println("Enter a number:\n");
Scanner input = new Scanner(System.in);
int a = input.nextInt();
for (int i = 2; i < a; i++) {
boolean primeNum = true;
for(int j=2; j<i; j++) {
if (i%j==0) {
primeNum =false;
}
}
if (primeNum) {
System.out.print(i + " ");
}
}
}
}
Look at proper sieves, like the Sieve of Eratosthenes. You don't need to be checking for % each time.
for(int j=2; j<i; j++) {
if (i%j==0) {
primeNum =false;
}
}
This is not a very efficient algorithm, but at the very least, put a break in there...
public static boolean [] createPrimes (final int MAX)
{
boolean [] primes = new boolean [MAX];
// Make only odd numbers kandidates...
for (int i = 3; i < MAX; i+=2)
{
primes[i] = true;
}
// ... except No. 2
primes[2] = true;
for (int i = 3; i < MAX; i+=2)
{
/*
If a number z is already eliminated
(like No. 9), because it is a multiple of -
for example 3, then all multiples of z
are already eliminated.
*/
if (primes[i] && i < MAX/i)
{
int j = i * i;
while (j < MAX)
{
if (primes[j])
primes[j] = false;
j+=2*i;
}
}
}
return primes;
}
updated after comment of Will Ness:
Improves the speed to about 2/1, it checks 100 Million ints in 5s on my 2Ghz single core.
private static void generatePrimes(int maxNum) {
boolean[] isPrime = new boolean[maxNum + 1];
for (int i = 2; i <= maxNum; i++)
isPrime[i] = true;
// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 2; i * i <= Math.sqrt(maxNum); i++) {
// if i is prime, then mark multiples of i as nonprime
if (isPrime[i]) {
for (int j = i; i * j <= maxNum; j++)
isPrime[i * j] = false;
}
}
// count primes
int primes = 0;
for (int i = 2; i <= maxNum; i++)
if (isPrime[i]) {
System.out.println("Prime - " + i);
primes++;
}
System.out.println("The number of primes <= " + maxNum + " is "+ primes);
}