I am in a beginner's java class. I have had this Yahtzee program now for weeks and I still cannot get this figured out.
Having problem getting a points from my checkTwopairs(). checkTwopairs() can see if there is a two pair. But I have a hard problem getting the points out of it. Any good way to do it?
public int checknumber(int nr) {
int sum = 0;
for (Dice d : diceList) {
if (d.getValue() == nr ){
sum++;
}
}
return sum;
}
public void checkTwopairs() {
for (int i = 1; i <= 6; i++) {
int a = checknumber(i);
if (a == 2) {
if (twopair == true && a == 2) {
} else {
twopair = true;
}
}
}
twopair = false;
}
I'm guessing you're looking for 2 pairs, meaning you get dice with {5,5,2,2,1} where you have 2 pairs -- a pair of 5's, and a pair of 2's.
I think you may be looking for something like this to modify your code:
public void checkTwopairs() {
boolean firstPair = false; // New local variable.
for (int i = 1; i <= 6; i++) {
int a = checknumber(i);
if (a == 2) {
//if (twopair == true && a == 2) <--- This second clause is unnecessary as we can only get here if a == 2
if (firstPair == true) {
twopair = true;
return; //This returns the method, so twopair cannot be set to false if two pairs are found
} else {
firstPair = true;
}
}
}
//Checked all dice, less than two pairs were found.
twopair = false;
}
Here is a one-method solution to replace both of those methods:
public void checkTwoPairs() {
int numPairs = 0;
//two pairs haven't been found yet
boolean twoPair = false;
//for each possible number
for(int i = 1; i <= 6; i++) {
int sum = 0;
//for each dice object
for(Dice d : diceList) {
//if i is the dice value
if(d.getValue() == i) {
//increment the number of matches
sum++;
}
}
//sum % 2 - gives you the number of pairs for that number checked
numPairs += (sum%2);
//if you have 2 pairs
if(numPairs == 2) {
//set twoPair = true ... and break out of the loop
twoPair = true;
break;
}
//if you don't have 2 pairs yet, go back through the loop
}
}
Related
I am struggling to understand why code wouldn't work. According to the truth table/logic gates for AND and OR https://en.wikipedia.org/wiki/Truth_table I would assume that I would be able to have an if statement inside the for-loop such that (p < 2 || p % i == 0) would work for finding prime numbers but it fails when considering negative numbers.
I know that if you if take out the p < 2 and write it as an if statement outside this for-loop it works, but if the p < 2 is inside the for-loop it does not work. Why is this so?
public class test {
public static void main(String [] args) {
System.out.println("Hello World!");
int a = 7;
System.out.println("A is Prime: " + isPrime(a));
System.out.println();
int b = 4;
System.out.println("B is Prime: " + isPrime(b));
System.out.println();
int c = -7;
System.out.println("C is Prime: " + isPrime(c));
System.out.println();
int d = 53;
System.out.println("D is Prime: " + isPrime(d));
}
public static boolean isPrime(int p) {
for (int i = 2; i < p; i++) {
if (p < 2 || p % i == 0) {
return false;
}
}
return true;
}
}
Because for p < 2, the body of the for loop is never performed. Indeed:
for (int i = 2; i < p; i++) {
// ...
}
If p = 2, then it initializes i = 2, and then checks i < p which fails, and hence the body is never executed. It skips the for loop, and thus returns true.
We can fix it by performing a check before (or after) the for loop, and even boost the performance of the loop slighly:
public static boolean isPrime(int p) {
if(p <= 2) {
return p == 2;
}
if(p % 2 == 0) {
return false;
}
for (int i = 3; i*i <= p; i += 2) {
if (p % i == 0) {
return false;
}
}
return true;
}
We can simply return false first for all values less than 2, and true for 2. Furthermore we only need to iterate up to √p, since if there is a value j larger than √p that divides p, then there is a smaller value i = p/j that is smaller than √p that will already be checked. We furthermore only need to check odd numbers, since even numbers are already implied by the division by 2.
You may want to invest in Math.abs(int):
public static boolean isPrime(int p) {
p = Math.abs(p);
for (int i = 2; i < p; i++) {
...
This will ensure that p is always non-negative, and your initial assumptions about how the loop should behave are justified.
I'm facing a problem and I'd like to know some ideas on how to solve it. I have a matrix of two dimensions and given a point on that matrix I need to look for ten cells up, down right, left and with diagonal movements (see the following image).
What I'm doing is selecting the values of i and j as the values to be multiplied by the position coordinates and give the direction that I want in each case. For example:
Diagonal A : i=1 j=-1 since i increases and j decreases
Diagonal B : i=1 j=1 since both increase
And for the vertical and horizontal movements i and j will take values 1 or 0.
Having these two values I can take the center and add a value to it starting this value to 1 and increasing it until I get to the limit (10). If the center is (2,4) and I'm in diagonal A I will add the value that is starting in one multiplied by i and j for each coordinate having the following results:
(3,3) (4,2) (5,1) (6,0)
Right now I am interested in computing i and j so that they take all the needed values for the diagonals and the axis. My java code that goes inside a loop is the following:
GS.r++;
if (GS.r > 10) {
GS.r = 0;
if (GS.iteration) {
int i = 0, j = 0;
if (GS.i == 1) {
i = -1;
} else if (GS.i == -1) {
i = 0;
j = 1;
}
if (GS.j == 1) {
j = -1;
} else if (GS.j == -1) {
j = 0;
i = 1;
}
GS.i = i;
GS.j = j;
if (GS.i == 1 && GS.j == 0) {
GS.iteration = false;
GS.i = -1;
GS.j = -1;
}
} else {
if (GS.i == 1 && GS.j == 1) {
GS.iteration = true;
GS.i = 1;
GS.j = 0;
} else {
if (GS.i == 1)
GS.j *= -1;
GS.i *= -1;
}
}
}
GS.i and GS.j are initialised as -1. And with this code I get first the diagonals since the values for GS.i and GS.j would be (-1,-1) (1, -1) (-1, 1) (1, 1) and then the axis having these values: (-1, 0) (1, 0) (0, -1) (0, 1).
I was wondering if there is a better way of generating i and j since my code is not that clean.
Thank you!
What I would do is create an enum for all the four directions you can move in that is Diagonal right up,Diagonal right down,Diagonal left up and Diagonal left down.
Sample code :
public enum Direction {
DIAGONAL_RIGHT_UP(1,1),
DIAGONAL_RIGHT_DOWN(1,-1),
DIAGONAL_LEFT_UP(-1,1),
DIAGONAL_LEFT_DOWN(-1,-1);
public int x;
public int y;
private Direction(int xCoordinateChange,int yCoordinateChange) {
x=xCoordinateChange;
y=yCoordinateChange;
}
}
Then use this to traverse.
public class CartesianCoordinate {
private long xCoordinate;
private long yCoordinate;
public CartesianCoordinate(long xCoordinate,long yCoordinate) {
this.xCoordinate=xCoordinate;
this.yCoordinate=yCoordinate;
}
public long getXCoordinate() {
return xCoordinate;
}
public long getYCoordinate() {
return yCoordinate;
}
public void moveCoordinateByStepSize(Direction direction,long stepSize) {
xCoordinate+=direction.x*stepSize;
yCoordinate+=direction.y*stepSize;
}
#Override
public int hashCode() {
int hashCode=0;
hashCode += (int)(xCoordinate-yCoordinate)*31;
hashCode += (int)(yCoordinate+xCoordinate)*17;
return hashCode;
}
#Override
public boolean equals(Object object) {
if(object == null || !(object instanceof CartesianCoordinate)) {
return false;
}
if( this == object) {
return true;
}
CartesianCoordinate cartesianCoordinateObject = (CartesianCoordinate)object;
if(xCoordinate == cartesianCoordinateObject.getXCoordinate() && yCoordinate == cartesianCoordinateObject.getYCoordinate()) {
return true;
}
return false;
}
#Override
public String toString() {
return "["+xCoordinate+","+yCoordinate+"]";
}
public CartesianCoordinate getAClone() {
return new CartesianCoordinate(xCoordinate,yCoordinate);
}
}
Now say you have a point (1,3) as a starting point. what you can do is for 100 iterations in a particular line.
CartesianCoordinate startingPoint = new CartesianCoordinate(1,3);
CartesianCoordinate rightUpDiag = startingPoint.getAClone(),leftUpDiag = startingPoint.getAClone(),rightDownDiag = startingPoint.getAClone(),leftDownDiag = startingPoint.getAClone();
for(int counter = 0 ;counter < 100; counter ++) {
System.out.println(rightUpDiag.moveCoordinateByStepSize(Direction.DIAGONAL_RIGHT_UP,1));
System.out.println(leftUpDiag.moveCoordinateByStepSize(Direction.DIAGONAL_LEFT_UP,1));
System.out.println(rightDownDiag.moveCoordinateByStepSize(Direction.DIAGONAL_RIGHT_DOWN,1));
System.out.println(leftDownDiag.moveCoordinateByStepSize(Direction.DIAGONAL_LEFT_DOWN,1));
}
i have made a java program for following problem statement -
"Dividing a set of numbers in to two sets such that sum of elements in each set must be equal "
input: array of integers
output:
"Yes"-if set can be divided in to two equal sum,
"No" -if can not be divided in to two equal sum,
"Invalid" -if integer array contains any other type of Integers(excepting positive integers)
and i have submitted the code to an online compiler and the code i have written has passed 8 test cases out of 10.i tried hard but i couldnt succeed finding those two test cases which failed . what are those two test-cases which failed ? here's the code -
public class CandidateCode {
public static String partition(int[] arr) {
int sum = getSum(arr);
int half = sum / 2;
int out = 0;
int i = 0;
boolean flag = false;
if (hasZero(arr)) {
return "Invalid";
}
if (sum % 2 != 0) {
return "No";
}
if (arr.length == 2) {
if (arr[0] == arr[1]) {
return "Yes";
}
return "No";
}
else {
while (i < arr.length) {
if (arr[i] < half)
out += arr[i];
if (out == half) {
flag = true;
break;
}
i++;
}
}
if (flag)
return "Yes";
else
return "No";
}
public static int getSum(int[] arr) {
int result = 0;
for (int i = 0; i < arr.length; i++) {
result += arr[i];
}
return result;
}
public static boolean hasZero(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] <= 0) {
return true;
}
}
return false;
}
}
One test case that would fail is an array consisting of:
4 8 4
I need to create a program that can get all the prime numbers from 1 to a large number. I have a getPrime method which returns true if the number is prime or false if it is not prime. When I use this method and a while loop to get a list of prime numbers from 1 to a large number it keeps returning 24 then 4 then 5.the variable end, in code below is asked for in a prime class runner separately. Here is my code:
public class Prime
{
private long userNumber;
private int numRoot;
private int x;
private boolean isPrime;
private int factors;
private long end;
private int i;
public void setUserNumber(long num)
{
userNumber = num;
}
public void setEndNumber(long n)
{
end = n;
}
public boolean getPrime()
{
numRoot = ((int)Math.sqrt(userNumber));
for (x=2; x<=numRoot; x++)
{
if ((userNumber % x) == 0)
{
factors++;
}
}
if (factors >1) {
isPrime = false;
}
else {
isPrime = true;
}
return isPrime;
}
public void getPrimeList()
{
if(end < 2) {
System.out.println("No prime numbers");
System.exit(0);
}
System.out.printf("\nThe prime numbers from 1 to %d are: \n 2", end);
Prime primeNum = new Prime();
i = 3;
while( i <= end )
{
userNumber = i;
getPrime();
if (isPrime == true)
{
System.out.println(userNumber);
}
i++;
}
System.out.println();
}
}
public void getPrimes(int N) {
for (int i = 2; i <= N; i++) {
if (isPrime(i)) System.out.println(i);
}
System.out.println("These are all the prime numbers less than or equal to N.");
}
private boolean isPrime(int N) {
if (N < 2) return false;
for (int i = 2; i <= Math.sqrt(N); i++) {
if (N % i == 0) return false;
}
return true;
}
The code below is written in C#, although it will work in Java with very little modification.
I use a long as the data type as you haven't been specific when you say "a large number".
public static bool isPrime(long Number)
{
if (Number == 1) { return false; }
int i = 2;
while (i < Number)
{
if (Number % i++ == 0) { return false; }
}
return true;
}
It can be applied like so, again this is C#, but will work in Java with little modification.
while (i <= LARGE_NUMBER)
{
Console.Write((isPrime(i) ? i.ToString() + "\n" : ""));
i++;
}
public class PrimeTest{
private static final int MAX_NUM = Integer.MAX_VALUE; // your big number
public static void main(String[] args) {
int count = 0;
for(int i=0; i<MAX_NUM; i++) {
if (isPrime(i)) {
System.out.printf("Prime number %d\n", i);
count++;
}
}
System.out.printf("There is %d prime numbers between %d and %d\n", count, 0, MAX_NUM);
}
public static boolean isPrime(int number) {
if (number < 2) {
return false;
}
for (int i=2; i*i <= number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
A prime number p should have zero factors between 2 and sqrt(p), but you are allowing one here:
if (factors >1){
isPrime = false;
}
In fact, there's no need to count factors at all, you can directly do
if ((userNumber % x) == 0) {
return false;
}
If you however need to count factors anyways, I would suggest setting factors explicitly to 0 at the start. It's not a good practice to rely on implicit initial values.
The problem is that you're using too many instance variables inside getPrime, causing you to unintentionally inherit state from previous iterations. More precisely, factors should be reset to 0 at the start of getPrime.
A better way to go about this is by making x, numRoot, isPrime and factors local variables of getPrime:
public boolean getPrime()
{
int factors = 0;
boolean isPrime;
int numRoot = ((int) Math.sqrt(userNumber));
for (int x=2; x<=numRoot; x++)
{
if ((userNumber % x) == 0)
{
factors++;
}
}
if (factors >1){
isPrime = false;
} else {
isPrime = true;
}
return isPrime;
}
You can go even further and make userNumber an argument of getPrime:
public boolean getPrime(int userNumber)
{
// ...
and call it with:
while( i <= end )
{
isPrime = getPrime(i);
if (isPrime)
{
System.out.println(userNumber);
}
i++;
}
Two things to note:
I removed the usage of userNumber inside getPrimeList completely, I simply use i instead.
The isPrime could be removed as well if it's not needed elsewhere, simply use if(getPrime(i)) { ... } instead.
Your algorithm is the wrong solution for your task. The task is to find all primes from 2 to N, the appropriate algorithm is the Sieve of Eratosthenes. (See here for an epic rant discussing basics and optimizations of sieve algorithms.)
It is known that all primes are either 2,3,5,7,11,13 or of the form
30*k-13, 30*k-11, 30*k-7, 30*k-1, 30*k+1, 30*k+7, 30*k+11, 30*k+13,
for k=1,2,3,...
So you generate an array boolean isPrime[N+1], set all to true and for any candidate prime p of the form above, until pp>N and if isPrime[p] is true, set all isPrime[kp]=false for k=2,3,4,...N/p.
int N;
Boolean isPrime[] = new Boolean[N+6];
static void cross_out(int p) {
for(int k=5*p, d=2; k<N; k+=d*p, d=6-d) {
isPrime[k]=false;
}
}
static void sieve() {
for(int k=0; k<N; k+=6) {
isPrime[k ]=isPrime[k+2]=false;
isPrime[k+3]=isPrime[k+4]=false;
isPrime[k+1]=isPrime[k+5]=true;
}
for(int k=5, d=2; k*k<N; k+=d; d=6-d) {
if(isPrime[k]) cross_out(k);
}
}
It now can find all the prime numbers in the input range, but it can't find number 2, the smallest prime number.
for(int number=2;number<range;number++){
for(int testDivide=2;testDivide<Math.sqrt(number);testDivide++){
if(number%testDivide!=0) {
System.out.println(number);
}
break;
}
For range 10 it prints:
5
7
9
but no 2.
The reason your code is not producing correct results (missing 2 and 3; including 9) is that your primality test logic is backwards. A number is prime if the inner loop completes without finding any even divisors; instead you are printing the number if you find any non-divisor.
Try this instead:
for( int number = 2; number < range; number++) {
boolean divisible = false;
int limit = (int) Math.sqrt(number);
for (int testDivide = 2; !divisible && testDivide <= limit; testDivide++) {
divisible = number % testDivide == 0;
}
if (!divisible) {
System.out.println(number);
}
}
Note that a much more efficient way to generate all primes in a range is the Sieve of Eratosthenes.
check the code here:
package core;
public class Test2 {
public static void main(String[] args) {
int cnt = 0;
for (int i = 2;; i++) {
if (Priem(i)) {
cnt++;
System.out.println(i);
if (cnt == 200)
break;
}
}
}
public static boolean Priem(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
Note that one of the best ways to generate a list of prime numbers is the "Sieve of Erwhatshisface":
Create a list of consecutive integers starting with 2, up to the max number you'd like to search. Take the first non-zero number in the list (2) and repeatedly step 2 from that location, zeroing out every 2nd list element.
Next take the second non-zero number (3) and repeatedly step 3 from that location, zeroing. Continue with each non-zero value in the list, until you've processed all of them (or at least halfway through, at which point you'll be stepping beyond the end of the list).
The non-zero numbers remaining are all primes.
Reposting code here as not fit in comments:
public static void main(String[] args) {
int cnt = 0;
for (int i = 2;; i++) {
if(i==2){
System.out.println(i);
continue;
}
if (Priem(i)) {
cnt++;
System.out.println(i);
if (cnt == 200)
break;
}
}
}
public static boolean Priem(int n) {
for (int i = 2; i <Math.sqrt(n)+1; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
I think you have your for loop a little mixed up.
for(int testDivide=2;testDivide<Math.sqrt(number);testDivide++){
}
Not sure why you are stopping when testDivide is equal to sqrt(number), you should stop when testDivide is greater than.
Also inside your inner for loop isn't correct either:
if(number%testDivide!=0) {
System.out.println(number);
}
break;
Basically all this will do is check to see of the number is divisible by 2 and then break. You only need to break when you find a number which cleanly divides (number%testDivide==0). Maybe keep a boolean which you set to true when you break and only print after the inner for loop finishes if that boolean is false.
Something along the lines:
for (int number=2; number<range; number++){
boolean found = false;
int limit = (int)Math.sqrt(number);
for (int testDivide=2; testDivide<=limit; testDivide++){
if(number%testDivide==0) {
found = true;
break;
}
}
if (!found) System.out.println(number);
}
In your code when number is 2, sqrt(2) is 1.41 and control doesn't go into the loop. I didn't get the logic behind iterating upto sqrt(number). Try this code
public class Test {
public static void main(String[] args) {
int range = 500; //I assume
for (int i = 2; i< range; i++) {
if (isPrime(i)) {
System.out.println(i);
}
}
}
public static boolean isPrime(int number) {
for (int i = 2; i <= number/2; i++) {
if (number % i == 0) {
return false;
}
if(i % 2 == 1) {
i++; //If not divided by 2 then
// need not to check for any even number
// Essentially incrementing i twice hereafter
}
}
return true;
}
}