I wonder if it is possible to have minimal code for this:
for (int x = 1; x < 10; x++){
/*I want to replace this condition with (x%number == 0)
instead of writing out condition for every number, but
it did not work with for (int number = 1; number <= 3; number++)
in (x%number == 0), as it prints out every x and number
*/
if ((x%1) == 0 && (x%2) == 0 & (x%3) == 0){
System.out.println(success!);
}
}
I think
x % a == 0 && x % b == 0 && x % c == 0
is equalent to
x % (a * b * c) == 0
UPDATE
Multiplication is incorrect, you need to use LCM: x % lcm(a, b, c)
Have a look :
for (int x = 1; x < 10; x++){
boolean flag = false;
for(int num = 1; num <= 3; num++){
if ((x%num) == 0 ){
flag = true;
}else{
flag = false;
break;
}
}
if(flag){
System.out.println(x + " success!");
}
}
OUTPUT :
6 success!
I know the code is looking a little horrified but will work for any value of x and num
This is what you'd need to make a comp sci professor happy:
for (int x = 1; x < 10; x++){
boolean success = true;
for (int number = 1; number <= 3; number++) {
if ((x % number) != 0) {
success = false;
}
}
if (success) {
System.out.println("success!");
}
}
although note: (x % 1) is always 0.
This is what you'd need to make me happy, according to my rule of "avoid nested loops":
for (int x = 1; x < 10; x++) {
if (testNumber(x))
System.out.println(x + " success!");
}
}
private static boolean testNumber(int x) {
for (int number = 1; number <= 3; number++) {
if ((x % number) != 0) {
return false;
}
}
return true;
}
Related
Can somebody help me a bit? I have trouble understanding why Boolean here doesn't work the way I want to. The idea is when i(firstnum) is odd, l(lastnum) to be equal and vice verse. Some help with how to use Boolean also will be a help, I can't understand it.
Input 3 and 5.
Expected output : 4333 4353 4443 4533 4553 5334 5354 5444 5534 5554
Actual output: 4333 4353 4443 4533 4553 5333 5334 5353 5354 5443 5444 5533 5534 5553 5554
int startNum = Integer.parseInt(scan.nextLine());
int endNum = Integer.parseInt(scan.nextLine());
boolean isItEqual = false;
boolean isItOdd= false;
int countDebugOperations = 0;
for (int i = startNum; i <=endNum ; i++) {
if (i % 2==0){
isItEqual =true;
}
for (int j = startNum; j <=endNum ; j++) {
for (int k = startNum; k <=endNum ; k++) {
for (int l = startNum; l <=endNum ; l++) {
if (l % 2 == 1){
isItOdd = true;
}
boolean flag =(i > l) && (j+k) % 2 ==0;
if(!isItEqual && (!isItOdd) && flag){
countDebugOperations+=1;
System.out.printf("%d%d%d%d ",i,j,k,l);
}
if (isItEqual && isItOdd && flag) {
countDebugOperations += 1;
System.out.printf("%d%d%d%d ", i, j, k, l);
}
You are trying to print numbers i, j, k and l in exactly two cases:
When i is even AND l is odd
When l is even AND i is odd
If we translate those cases to code (boolean expressions), we get:
i % 2 == 0 && l % 2 == 1
l % 2 == 0 && i % 2 == 1
Now, when we iterate through for loops, we can ask if our "number state" matches one of those 2 cases (first case OR second case).
int startNum = Integer.parseInt(scan.nextLine());
int endNum = Integer.parseInt(scan.nextLine());
for (int i = startNum; i <= endNum; i++) {
for (int j = startNum; j <= endNum; j++) {
for (int k = startNum; k <= endNum; k++) {
for (int l = startNum; l <= endNum; l++) {
boolean firstCase = i % 2 == 0 && l % 2 == 1;
boolean secondCase = l % 2 == 0 && i % 2 == 1;
// now when we print, we can ask if we are in the first OR the second case
if (firstCase || secondCase) {
System.out.printf("%d%d%d%d ",i,j,k,l);
}
}
}
}
}
I'm making a simple "Whack a mole" game in Java. For simplicity I have created a 10*10 box and placed 10 moles in random boxes. I want to exit the game when the user spent his 50 inputs or found all 10 moles, but there seems to be a problem in terminating the while loop even when the user attempts specified inputs.
Is it Instance variable scope problem? Why it is not working?
public class WhackAMole {
int score = 0, molesLeft = 10, attempts;
char[][] moleGrid = new char[10][10];
int numAttempts, gridDimension;
public WhackAMole(int numAttempts, int gridDimension) {
// TODO Auto-generated constructor stub
this.numAttempts = numAttempts;
this.gridDimension = gridDimension;
}
boolean place(int x, int y) {
return (x == 2 && y == 5)
|| (x == 1 && y == 3)
|| (x == 8 && y == 4)
|| (x == 5 && y == 10)
|| (x == 6 && y == 9)
|| (x == 10 && y == 7)
|| (x == 3 && y == 7)
|| (x == 2 && y == 9)
|| (x == 4 && y == 8)
|| (x == 9 && y == 5);
}
void whack(int x, int y) {
if (place(x, y)) {
if (moleGrid[x - 1][y - 1] == 'W') {
System.out.println("Already attempted! \'try other co-ordinates\' \n");
} else {
moleGrid[x - 1][y - 1] = 'W';
this.score ++;
this.molesLeft --;
}
}
}
void printGridToUser() {
System.out.println("your score is " + score + " and " + molesLeft + " moles are left. \n");
System.out.println("input x = -1 and y = -1 to quit the game! \n");
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
System.out.print(" " + moleGrid[i][j] + " ");
}
System.out.println("\n");
}
}
void printGrid() {
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
this.moleGrid[i][j] = '*';
}
}
}
public static void main(String[] args) {
WhackAMole game;
System.out.println("Lets play the Whack A Mole!\n");
game = new WhackAMole(50, 100);
game.printGrid();
game.printGridToUser();
Scanner scanner = new Scanner(System.in);
while ((game.numAttempts > 0) || (game.molesLeft > 0)) {
System.out.println("Enter box co-ordinate\n");
System.out.println("x co-ordinate: \n");
int x = scanner.nextInt();
System.out.println("y co-ordinate: \n");
int y = scanner.nextInt();
if (x == -1 && y == -1) {
break;
} else if ((x < 1 || y < 1) || (x > 10 || y > 10)) {
System.out.println("please enter values of x and y greater than 0 and less than 11! \n");
} else {
game.whack(x, y);
game.numAttempts--;
game.gridDimension--;
System.out.println("you can have upto " + game.numAttempts + " out of " + game.gridDimension + " boxes \n");
game.printGridToUser();
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (game.place(i+1, j+1) && game.moleGrid[i][j] != 'W'){
game.moleGrid[i][j] = 'M';
}
}
}
game.printGridToUser();
scanner.close();
System.out.println("game over!!!\n");
}
}
Your while loop is not ending because you are using || in your while loop. The || is making your loop run until the attempts allowed i.e. 50 and the right guessing i.e. finding moles correct both are met. So even when a gamer has finished his allowed attempts and hasn't guessed all the right moles positions, the loop will not end
The simple solution would be to replace || with &&
while ((game.numAttempts > 0) && (game.molesLeft > 0))
And avoid using fixed numbers i.e. 10 in your for loops instead use
for (int i = 0; i < game.gridDimension; i++) {
for (int j = 0; j < game.gridDimension; j++) {
I hope it helps
Your loop is using an or for the test function. This means both condition mist be false in order for it to stop. In your case. How its written you must exhaust the numtries and have no moles left.
Change to use && vs ||.
I'm trying to make a while loop that iterates through every long number possible and add every prime number it encounters into an the primes array. Since the while loop is supposed to run until the length of primes is 200, I expect the primes array to be filled with the first 200 prime numbers. Instead I get all zeroes. I have successfully gotten 20 rows of 10 characters each with a space in between them. How may I get them to be the actual prime numbers though?
public class PrimeGenerator {
public static void main(String[] args) {
long primes[] = new long[200];
while (primes.length > 200){
for(long y = 2; y < Long.MAX_VALUE; y++) {
int primeCounter = 0;
if (isPrime(y) == true){
primes[primeCounter] = y;
primeCounter++;
}
}
}
for (int i = 0; i < 20; i++) {
int primeCounter = 0;
for(int p = 0; p < 10; p++) {
System.out.print(primes[primeCounter] + " ");
primeCounter++;
}
System.out.println();
}
}
public static boolean isPrime(long number) {
if (number % 2 == 0)
return false;
if (number == 2)
return true;
for(int x = 3; x*x <= number; x+=2) {
if (number%x == 0)
return false;
}
return true;
}
}
primes.length is always 200 so the while loop is never entered.
The while loop is useless. Just add a condition to the for loop that would exit when the entire array has been assigned. Also move the initialization of primeCounter to be outside the for loop. Otherwise all the primes will be assigned to primes[0].
long primes[] = new long[200];
int primeCounter = 0;
for(long y = 2; y < Long.MAX_VALUE && primeCounter < 200; y++) {
if (isPrime(y) == true){
primes[primeCounter] = y;
primeCounter++;
}
}
for (int i = 0; i < primes.length; i++) {
System.out.print(primes[i]);
if ((i+1) % 10 == 0)
System.out.println();
}
EDIT :
As Sweeper commented, you should also fix your isPrime method, since it returns false for 2 :
public static boolean isPrime(long number) {
if (number == 2)
return true;
if (number % 2 == 0)
return false;
for(int x = 3; x*x <= number; x+=2) {
if (number%x == 0)
return false;
}
return true;
}
this code down
long primes[] = new long[200];
while (primes.length > 200){
means
while (200 > 200){
or the same as
while (false){
so your loop is NEVER executed!
because you did:
while (primes.length > 200)
and the length of the array is always 200,you never get into the while loop , and the zero in the array are coming because when you create array of "long" it initialized him with zeros
Firstly, the length of an array doesn't change. So, when you are testing for primes.length > 200 this will always be false, and the loop is never even entered. Therefore all values in the array are left at the default value of 0.
For doing this I would doing something like the following:
int primeCounter = 0;
long current = 0L;
while(primeCounter < primes.length){
if(isPrime(current)){
primes[primeCounter] = current;
primeCounter++;
}
current++;
}
An array's length never changes. If you declared an array to have a length of 200, it will always have a length of 200. Because of this, your while loop is never executed, not even once.
There are a lot of other errors in the code, so I tried to create a solution with as few changes as possible:
public static void main(String[] args) {
int primeCounter = 0;
long nextPossiblePrime = 2;
long primes[] = new long[200];
while (primeCounter < 200) {
for (long y = nextPossiblePrime; y < Long.MAX_VALUE; y++) {
if (isPrime(y) == true) {
primes[primeCounter] = y;
primeCounter++;
nextPossiblePrime = y + 1;
break;
}
}
}
primeCounter = 0;
for (int i = 0; i < 20; i++) {
for (int p = 0; p < 10; p++) {
System.out.print(primes[primeCounter] + " ");
primeCounter++;
}
System.out.println();
}
}
public static boolean isPrime(long number) {
if (number == 2 || number == 3)
return true;
if (number % 2 == 0)
return false;
for (int x = 3; x * x <= number; x += 2) {
if (number % x == 0)
return false;
}
return true;
}
The first problem is that you created two primeCounters, which is not needed. I removed the extra one and moved the scope of it to the scope of the method. The next problem is that your first for loop doesn't remember the prime number that it is on and it doesn't stop when it has found one so it will keep adding the 200th prime to the array. I fixed this by adding a nextPossiblePrime variable that stores what number should the program check next. The last problem is that your isPrime method is written incorrectly. I fixed it for you!
Here's another (cleaner) solution, which still uses a while loop:
public static void main(String[] args) {
ArrayList<Long> primes = new ArrayList<>();
long y = 2;
while (y < Long.MAX_VALUE && primes.size() < 200) {
if (isPrime(y) == true){
primes.add(y);
}
y++;
}
for (int i = 0; i < primes.size(); i++) {
System.out.print(primes.get(i) + " ");
if ((i+1) % 10 == 0)
System.out.println();
}
}
public static boolean isPrime(long number) {
if (number == 2 || number == 3)
return true;
if (number % 2 == 0)
return false;
for (int x = 3; x * x <= number; x += 2) {
if (number % x == 0)
return false;
}
return true;
}
I have a little problem with my java code! The question is: The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
My code somehow doesn't work!! What's wrong? Thanks for your help!
public class Example_1 {
public static void main (String[] args){
{
System.out.println(largestPrimeFactor(600851475143));
}
}
private static long largestPrimeFactor(long number) {
long result = 0;
for(long x = 2;x<number;x++){
if(number % x == 0){
for( long y = 2; y < x ; y++ ){
if( x % y == 0){
break;
}
else{
result = x;
}
}
}
}
return result;
}
}
for( long y = 2; y < x ; y++ ){
if( x % y == 0){
break;
}
else{
result = x;
}
}
Here you are trying to test whether x is prime. However, if you follow this loop logic through, you will see that it translates to the following:
If any y is found not to be a factor of x before it is discovered whether or not x is prime, then x is prime.
Refactor the else to outside the loop.
boolean xIsPrime = true;
for( long y = 2; y < x ; y++ ){
if( x % y == 0){
xIsPrime = false;
break;
}
}
if( xIsPrime ){
result = x;
}
Compilation problems:
The method largestPrimeFactor appears to be outside of a class.
The constant 600851475143 is too large for an int. Postfix with L: 600851475143L.
Note that the algorithm you've written is suboptimal and that is why it may run for a long time when given large inputs.
public class Example_1 {
public static void main (String[] args){
System.out.println(largestPrimeFactor(600851475143L));
}
private static long largestPrimeFactor(long number) {
long result = 0;
if (number % 2 == 0){
result = 2;
while (number % 2 == 0)
number /= 2;
}
for(long x = 3; number > 1; x += 2)
if (number % x == 0){
result = x;
while (number % x == 0)
number /= x;
}
return result;
}
}
I've wrote a little program to generate numbers that have 2 conditions:
has all digits from 1 tot 9 so a number like 123456789
the number must be divisible by the last digit
for example 442 because 4 % 2 == 0 and 4 % 4 == 0
This is my backtrack algorithm:
static void backTrack(int value)
{
//Check if the number has all 9 digits, that it is dividable
if(isNine(value) && isDiv(value))
{
//System.out.println(value);
System.out.println("Found solution.");
System.out.println(aantal);
aantal++;
}
else
{
if(howMany(value) >= 9)
return;
for(int i = 1; i < 10; i++)
{
value = value * 10 + i;
if(value % i == 0 && howMany(value) <= 9)
{
//System.out.println(value);
backTrack(value);
}
value = value / 10;
}
}
}
//Gives length of integer for example 124 must give 3, 13 gives 2
static int howMany(int value)
{
int test = value % 10;
value = value / 10;
int teller = 0;
while(test != 0)
{
teller++;
test = value % 10;
value = value / 10;
}
return teller;
}
//Checks if the number is dividable by the last digit of the number and keeps recursive doing this for the whole number so 442 = YES 235 = NO
static boolean isDiv(int value)
{
int test = value % 10;
value = value / 10;
while(test != 0)
{
if(value % test == 0)
{
test = value % 10;
value = value / 10;
}
else
return false;
}
return true;
}
//Checks if the number has all digits from 1 to 9
static boolean isNine(int value)
{
boolean values[] = new boolean[10];
int test = value % 10;
int counter = 0;
for(int i = 1; i < values.length; i++)
values[i] = false;
while( test != 0)
{
if(values[test])
return false;
else
{
values[test] = true;
value = value /10;
test = value % 10;
}
}
for(int i = 1; i < values.length; i++)
{
if(values[i])
counter++;
}
if(counter == 9)
return true;
else
return false;
}
It never comes to a solution, I tested all subfunctions and those are working great.
Is there something wrong with my backtracking scheme? The System.out.println(aantal) is just a var to count how many solutions I've found.
I start with backtrack(0);
static void backTrack(int value)
{
//Check if the number has all 9 digits, that it is dividable
if(isNine(value)) // CHANGED this if test.
{
System.out.println("Found solution.");
System.out.println(value);
aantal++;
}
else
{
if(howMany(value) >= 9)
return;
for(int i = 1; i < 10; i++)
{
value = value * 10 + i;
if(value % i == 0 && howMany(value) <= 9)
{
//System.out.println(value);
backTrack(value);
}
value = value / 10;
}
}
}
//Gives length of integer for example 124 must give 3, 13 gives 2
static int howMany(int value)
{
int test = value % 10;
value = value / 10;
int teller = 0;
while(test != 0)
{
teller++;
test = value % 10;
value = value / 10;
}
return teller;
}
//Checks if the number has all digits from 1 to 9
static boolean isNine(int value)
{
boolean values[] = new boolean[10];
int test = value % 10;
int counter = 0;
for(int i = 1; i < values.length; i++)
values[i] = false;
while( test != 0)
{
if(values[test])
return false;
else
{
values[test] = true;
value = value /10;
test = value % 10;
}
}
for(int i = 1; i < values.length; i++)
{
if(values[i])
counter++;
}
if(counter == 9)
return true;
else
return false;
}
}