"Yahtzee" game Java Programming [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
My assignment is to make "Yahtzee" game on Java Program.
I am almost done except the Small Straight method. (Cannot figure it out.)
Small Straight is when the dice got 4 straight number. (Ex. 12334, 23345, 34556, and etc.)
Here is my code of isSmallStraight method (This code is not completed!):
public static boolean isSmallStraight(List<Die> dice) {
boolean result = false;
List<Die> copy = new ArrayList<Die>(dice);
Collections.sort(copy);
List<Die> testCase1 = new ArrayList<Die>();
testCase1.add(new Die(1));
testCase1.add(new Die(2));
testCase1.add(new Die(3));
if(copy.containsAll(testCase1)) {
result = true;
System.out.println(result);
}
return result;
}
What I want to do in here is I passed 5 random numbers of dice from the main method (List dice) and put them into the "copy" object.
Since I need to use java.util.List.containsAll() method(requirement), I think I need to make one other object "testCase1" to compare with "copy". (If you have other method to solve this question, it is fine at least you use java.util.containsAll() method.)
However, what I don't know right now is if I use dice.add(new Die(3)), it means the program picks random numbers from 1,2, and 3. (Not die number 3) - Also, it gave me compile-time error.
So, I want to know how I can store dice specific number 1,2,3, and 4 for "testCase1", 2,3,4, and 5 for "testCase2", and 3,4,5, and 6 for "testCase3" and use copy.containsAll(testCase1) becomes true.
Please help me as soon as possible!
PS. Die class is already programmed by my professor. (So, cannot change any in the Die class).

Put the numbers into a TreeSet to get rid of duplicates and get sorting for free.
You have 4 straight dice if:
The set contains exactly 4 numbers
The difference between the largest and the smallest is 3

The method I like to use (for large and small straights as well as all other scoring) is to create a new int array from the int array that holds the dice values. Like this:
int[] numDice = new int[6];
for (int i: diceValues)
numDice[i-1] += 1;
This counts up all your dice and puts the number of each, in order, in a new array. For instance, if the 5 dice you rolled were 3, 4, 3, 1, and 6, your new array would be {1, 0, 2, 1, 0, 1}, and a yahtzee of all 4s would turn into {0, 0, 0, 5, 0, 0}. From this new array it's fairly trivial to determine all of the scores. For straights:
int straightCount = 0;
for (int i: numDice) {
if (i > 0)
straightCount++;
else
straightCount = 0;
if (straightCount > 3)
smallStraight = true;
if (straightCount > 4)
largeStraight = true;
}
If you wanted to you could use this array to easily determine all the valid scores in one short method, and store the booleans in a single array.

Related

I am trying to solve this leetcode problem [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Question :
Given the number k, return the minimum number of Fibonacci numbers whose sum is equal to k, whether a Fibonacci number could be used multiple times.
The Fibonacci numbers are defined as:
F1 = 1
F2 = 1
Fn = Fn-1 + Fn-2 , for n > 2.
It is guaranteed that for the given constraints we can always find such fibonacci numbers that sum k.
Link to question:
https://leetcode.com/problems/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/
Example :
Input: k = 7
Output: 2
Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
For k = 7 we can use 2 + 5 = 7.
class Solution {
public int findMinFibonacciNumbers(int count) {
PriorityQueue<Integer> num=new PriorityQueue<>(Collections.reverseOrder());
int i1=1,i2=1;
num.add(i1);
num.add(i2);
int k=count;
int i3=0;
k=k-2;
int res=0;
while(k>=1){
i3=i2+i1;
num.add(i3);
int temp=i2;
i2=i3;
i1=temp;
k--;
}
while(count!=0){
int n=num.poll();
if(n<=count)
{ res++;
count-=n;
}
}
return res;
}
}
It says wrong output for 'input=3'. I generated the fibonacci series and traversed from highest number to find numbers less than or equal to sum. It will be really helpful if somebody helps me.
Thank you in advance.
You can simply use recursion for this problem.
This'll pass through:
class Solution {
public int findMinFibonacciNumbers(int k) {
if (k < 2)
return k;
int first = 1;
int second = 1;
while (second <= k) {
second += first;
first = second - first;
}
return 1 + findMinFibonacciNumbers(k - first);
}
}
References
For additional details, you can see the Discussion Board. There are plenty of accepted solutions with a variety of languages and explanations, efficient algorithms, as well as asymptotic time/space complexity analysis1, 2 in there.
If you are preparing for interviews:
We would want to write bug-free and clean codes based on standards and conventions (e.g., c1, 2, c++1, 2, java1, 2, c#1, 2, python1, javascript1, go1, rust1). Overall, we would like to avoid anything that might become controversial for interviews.
There are also other similar platforms, which you might have to become familiar with, in case you'd be interviewing with specific companies that would use those platforms.
If you are practicing for contests1:
Just code as fast as you can, almost everything else is very trivial.
For easy questions, brute force algorithms usually get accepted. For interviews, brute force is less desired, especially if the question would be an easy level.
For medium and hard questions, about 90% of the time, brute force algorithms fail mostly with Time Limit Exceeded (TLE) and less with Memory Limit Exceeded (MLE) errors.
Contestants are ranked based on an algorithm explained here.

Sorting values off array in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am new to this site and new to java so pleas help me out. If i have array of positive and negative numbers all are int,
how to sort all the positive ones in a new array and all negative in a other new array.
Asking a question in StackOverflow without any selfstudy on basics would attract downvotes. Kindly take time in doing your research. However to make you understand the way to solve I am providing you with a solution.
Step 1: You have an array of positive and negative values
Integer[] initialArray = new Integer[10];
//This contains the list of all values.
Step 2: Create two ArrayLists to save the negative and positive values in each of these.
ArrayList<Integer> positiveValues = new ArrayList<>();
ArrayList<Integer> negativeValues = new ArrayList<>();
Step 3: Iterate through initialArray and save the respective values in both lists.
for(int i =0; i< initialArray.length; i++) {
if(initialArray[i] < 0) {
negativeValues.add(initialArray[i]);
} else {
positiveValues.add(initialArray[i]);
}
}
Step 4: Now sort the values
Collections.sort(negativeValues);
Collections.sort(positiveValues);
Step 5: If Required If you need in arrays instead of ArrayList,
Integer[] negativeArray = new Integer[negativeValues.size()];
Integer[] positiveArray = new Integer[positiveValues.size()];
And cast these to get the array
I actually think this is a pretty good question. Here is an implementation you can try using Java 8 streams.
Given an integer array full of mixed negative/positive numbers:
int[] a = new int[] { 5, 6, 7, 4, -2, 5, -9, 2 };
One solution could be as follows:
int[] pos = Arrays.stream(a).filter(i -> i >= 0).sorted().toArray();
int[] neg = Arrays.stream(a).filter(i -> i < 0).sorted().toArray();
The pos[] array will have all the positive numbers sorted, and neg[] all the negative numbers sorted. The only thing I really dislike is that a[] is traversed twice, but at least it is short.
First seperate positive and negative numbers. I mean find size of positive numbers and create-set new positive numbers array. Then find size of negative numbers and create-set new negative numbers array.
Then just call sort method on both arrays.
Arrays.sort(array);

I need assistance with understanding the / and % symbol from Java. Also, I need some advice on how to proceed with the code [duplicate]

This question already has answers here:
How can I improve this code for Project Euler 7?
(4 answers)
Closed 7 years ago.
Alright, let us start off, by showing my question.
The Problem:
10001st prime
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
This is what I currently have down. I'm pretty bad at creating algorithms, but I truly have the desire to follow in my Father's path of being a IT. I enjoy doing this a lot, but I'm struggling right now.
public class PrimeNumber
{
public static void main(String[] args)
{
int primeNum = 2;
for (int count = 0; count < 10002; count++)
{
if (primeNum / 2 == && primeNum / primeNum == 1)
{
primeNum++;
}
else
{
System.out.println("Error.");
}
}
System.out.println(primeNum);
}
}
The / symbol means 'divided by'. So your code says 'if primeNum divided by 2 = 1 and primeNum divided by primeNum = 1 then increase primeNum.' This is unnecessary; all this is asking is if primeNum is 2.
The % symbol means 'remainder when divided by'. So 2%3 = 1. 4%2=0. This will probably be useful in your program, because it will allow it to check to see if your number is prime by seeing if it is divisible by any numbers.
(With if (a%b==0), you can check to see if b is a factor of a.)
There are a few shortcuts your program could take: it only needs to check every prime number up to the square root of the number it is checking.
So you may want to keep an array of all prime numbers you have found, so that you can check if a number you want to know if it's prime is divisible by any of them.
(This can be done with a loop on the outside, going through every number, and a loop inside that loop, checking to see if that number is divisible by any of the previously discovered prime numbers.)

Random numbers between my own values [duplicate]

This question already has an answer here:
Select a random value from an Array
(1 answer)
Closed 8 years ago.
I'm writing a program that generates co-primes of a number.
Now for example a number 'A' has 50 co-primes, my objective is to randomly select a co-prime from the list of all co-primes generated for the number A.
Again for example:
consider a number 15, it has co-primes - {1, 2, 4, 7, 8, 10, 11, 13, 14}. So now i have to select randomly from these values. Likewise, if i generate an array of any values, then how to randomly select from this array.
So in general my question is how to generate a random number from the array of numbers that i have. Now, those numbers in the array can be anything. Like not necessarily natural numbers, or prime numbers, etc.
So is there any java function to do so. I've burnt my brain searching the internet, but didn't find one. I usually go for finding result on google, rather than asking quetions on forums. But when one gets exhausted, it's better to ask experts out there who might have faced similar problems.
Thanks in advanced!!
Is that what you want ?
int[] arr = { 1,5,9,3,2,7 };
Random rd = new Random();
int dice = arr[rd.nextInt(arr.length)];
You can use the java.util.Random class for this:
public int chooseRandom(int[] coPrimes) {
//Creates the Random instance
Random randomizer = new Random();
//Generate a random integer between 0 and the length of the array (exclusive)
int value = randomizer.nextInt(coPrimes.length);
//Return the element at that generated index
return coPrimes[value];
}

changing values inside the array in java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Good evening
i'm trying to solve a question which is :
You are given a int[] marks containing the grades you have received so far in a class. Each
grade is between 0 and 10, inclusive. Assuming that you will receive a 10 on all future
assignments, determine the minimum number of future assignments that are needed for you to
receive a final grade of 10. You will receive a final grade of 10 if your average grade is 9.5 or
higher.
Definition Class: AimToTen Method: need Parameters:
int[] Returns: int Method signature: int need(int[]
marks) (be sure your method is public) Examples 1)
{9, 10, 10, 9} Returns: 0 Your average is already 9.5, so no
future assignments are needed. 2) {8, 9} Returns:
4 In this case you need 4 more assignments. With each
completed assignment, your average could increase to 9, 9.25, 9.4
and 9.5, respectively
My attempt to solve is :
public int need(int[] marks) {
int i=0, sum = 0, avg = 0, k = 0, counter = 0, ToCompleteMarks[] = null;
for (i; i < marks.length; i++) {
sum = sum + marks[i];
ToCompleteMarks[i] = marks[i] + ToCompleteMarks[i];// To copy the array so when i add 10 later to the program the original array does not change > good ?
}
avg = sum / marks.length;
while (avg < 9.5)
ToCompleteMarks[i]; //I need to add the number 10 to the array then get back to calculate the avg . But no ideas how to do that ! .
counter++;
return counter;
}
if you could help me with that I would be really greatful
thanks
We can do the below mentioned steps:
1. Get the difference between the avg calculated and the desired average(9.5)
LEts say that the calculated average is 8.
Difference would be 9.5-8 = 1.5
Hence we can take the upper limit(ceiling value) of the difference using Math.ceil(difference). Here it would be 2. Thus we need to add two assignments to the array.

Categories