I have to make a Poker Dice game for class. I am able to successfully random five numbers 1 to 6 (to resemble rolling a die five times). However, I need to show "Nine" for 1, "Ten" for two, etc. I am using an array to hold the numbers. I can't seem to figure out how to assign a string output for each int.
public static void main(String[] args) {
int[] player = new int[5];
String[] cards = new String[] {"Nine", "Ten", "Jack", "Queen", "King", "Ace"};
System.out.println("User: " + playerHand(player, cards));
}
public static String playerHand(int[] player, String[] cards) {
String hand = "";
for (int i = 0; i < player.length; i++) {
player[i] = (int) (Math.random() * (6 - 1) + 1);
hand += player[i] + " ";
}
return hand;
}
You've put your strings in an array, so you just add an element from the array to your hand string:
hand += cards[player[i]] + " ";
There is, however, still a problem with your code. You obtain the random numbers as follows:
player[i] = (int) (Math.random() * (6 - 1) + 1);
You probably expect this to be a number from 1 to 6. However, Math.random() returns a double from 0 (inclusive) to 1 (exclusive). That means that player[i] will never be assigned 6. This error kind of solves another error: since Java arrays are zero-based, the element with index 6 does not exist. (Thus, if 6 would have been chosen, your program would have aborted with an error message.) But still, the number 0 and thus the word "Nine" will never appear in your solution. So you have to change the two lines to:
hand += cards[player[i] - 1] + " ";
and
player[i] = (int) (Math.random() * 6 + 1);
respectively.
Consider making the cards array a static class member; then you don't need to pass the array to the playerHand method as an argument.
You might use a switch block
switch(array[i]){
case 1:
printf("One\n");
break;
case 2:
printf("Two\n");
break;
etc...
Related
I searched up the code and logic for this and basically copied the code from https://www.youtube.com/watch?v=k4y5Pr0YVhg
and https://www.techiedelight.com/coin-change-problem-find-total-number-ways-get-denomination-coins/
But my program is wrong because there are definitely more than 2 ways to make 2 pounds.
public class TwoPounds
{
private static int[] coins = {1, 2, 5, 10, 20, 50, 100, 200};
private static int amount;
private static int count;
public TwoPounds()
{
amount = 2;
count = 0;
}
public static void main(String[] args)
{
TwoPounds run = new TwoPounds();
count = run.combos(amount);
run.printOut();
}
public int combos(int amountIn)
{
if (amountIn == 0)
{
return 1;
}
if (amountIn < 0)
{
return 0;
}
int combosCount = 0;
for(int i = 0; i < coins.length; i++)
{
System.out.println("amountIn now is " + amountIn);
combosCount += combos(amountIn - coins[i]);
}
return combosCount;
}
public void printOut()
{
System.out.println("\n\n\n");
System.out.println("There are " + count + " ways can 2 pounds be made, "
+ "using any number of coins");
System.out.println("\n\n\n");
}
}
Output:
There are 2 ways can 2 pounds be made, using any number of coins
Your coins are in cents (or pence, since I guess you are using GB Pounds), so since you are performing amountIn - coins[i] with them, that means that your amount is cents/pence as well.
So, change your amount to the :
amount = 200;
It is worth taking a moment to consider variable naming, and how that might have helped identify - or even avoid - this problem altogether. The terms "amount" and "amountIn" are ambiguous.
Nothing in the words suggests the units. So, get into the habit of making variable names as specific and unambiguous as possible - and include units where appropriate.
eg, if the variables were called 'amountInPounds', then the error becomes more obvious when writing amountInPounds - coins[i]
Now, before you do update to amount = 200;, be aware that :
1) There will be a LARGE number of results (200 pennies, 198 pennies+2p), that will take some time to iterate through one-penny-at-a-time, plus
2) Your code is currently written to go through EVERY discrete ordered combination - eg, it will be counting :
198 "1 cent" + 1 "2 cent"
197 "1 cent" + 1 "2 cent" + 1 "1 cent"
196 "1 cent" + 1 "2 cent" + 2 "1 cent"
195 "1 cent" + 1 "2 cent" + 3 "1 cent"
etc
Again, WAY too much execution time. What you want is to not start your for(int i = 0; i < coins.length; i++) from zero each time, but instead add an extra parameter to combos - so something like :
public int combos (int amountIn, int startCoin)
{
// blah ... existing code ... blah
for(int i = startCoin; i < coins.length; i++)
{
System.out.println("amountIn now is " + amountIn);
combosCount += combos(amountIn - coins[i], i);
}
Finally, as I said before, 200 will result in BIG numbers that will be effectively impossible for you to confirm correctness, so instead start with small amounts that you can check.
This algorithm allows the use of several coins of the same denomination, so there are 2 ways to make 2 pounds:
{1, 1}
{2}
I have a small problem when trying to generate a random string with random size (between 3 and 20). I have an array arr with all characters from a (lowercase) to Z (uppercase). I then generate a random length arrLength for a second array arr2, which will be containing some randomly selected chars.
My issue is that the letter 'a' (lowercase) never appears in my randomly generated strings. I think that the mistake might be inside the for loop, but I have failed to see it so far. Maybe it has something to do with (int) casting or Math.floor rounding?
char[] arr = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
int arrLength = (int) (Math.floor((Math.random() * ((17 - 3) + 1)) + 3));
char[] arr2 = new char[arrLength];
String str = "";
for(int i=0;i<arrLength;i++) {
char num = arr[(int) (Math.floor(Math.random() * (50) + 1))];
arr2[i] = num;
}
Instead of the magic constant 50 use arr.length (note there are more than 50 characters in the array) and leave out the +1 as it makes the lowest number you can get to 1 and array indices start at 0 in Java.
This question already has answers here:
Non repeating random numbers
(2 answers)
Closed 8 years ago.
I've made a random wrestling match generator that I've adapted from a random phrase generator from a textbook. I'd like to know how to make it so the same name isn't done twice on the same run. Can't have The Crusher vs. The Crusher, right?
public class matchOMatic {
public static void main (String [] args) {
String [] wordListOne = {"The Crusher", "The Main Man", "The Macho-man, Randy Savage", "The Nature Boy, Rick Flare", "Batista", "Hollywood Hulk Hogan", "Vader", "The Undertaker", "Stone Cold Steve Austin" };
String [] wordListThree = {"The Crusher", "The Main Man", "The Macho-man, Randy Savage", "The Nature Boy, Rick Flare", "Batista", "Hollywood Hulk Hogan", "Vader", "The Undertaker", "Stone Cold Steve Austin"};
int oneLength = wordListOne.length;
int threeLength = wordListThree.length;
int rand1 = (int) (Math.random() * oneLength);
int rand3 = (int) (Math.random() * threeLength);
String phrase = wordListOne[rand1] + " and in the opposite corner is his opponent, " + wordListThree[rand3];
System.out.print("In this corner we have " + phrase);
System.out.println("!");
}
}
Very simple solution for this!
Just put this after you give values to rand3 and rand2:
while(rand3 == rand1) {
rand3 = (int) (Math.random() * threeLength);
}
This will keep choosing a new value for rand3 until the values are different!
I hope this helps. Good luck with your program :)
The cleanest solution is to store the names in an ArrayList rather than an array of strings, shuffle the list, and iterate through in pairs to create matches. Shuffling a list of length N is O(N), and this is guaranteed to not produce duplicates across the scheduled matches.
You could pick the next one ( or the one before) if the random turns out to be the same.
if ( rand3 == rand1 )
rand3 = (rand3 +1) % threeLength
Edit:
As noted below this creates bias which is not good.
other possible solution is not to include the first randomly picked index in the next random roll
// -1 because we are not including the same pick
int rand3 = (int) (Math.random() * ( threeLength-1) );
// fix the index because we haven't actually removed it from the array
if (rand3 >= rand1)
rand3 = (rand3 +1) % threeLength
I have a lot of Strings, like l1 or l23.
Now I want to print out a random string, e.g. l3.
I have already written code for a random number:
int r = 1 + (int)(Math.random() * ((30 - 1) + 1));
So, now I want to print a string which's variable name is the letter l plus the random integer r.
Is this possible?
You can use an array
long[] l = new long[30];
int r = // 1 to 29;
System.out.println("l" + r + ": " + l[r]);
You can use array. Index can be choosen in random manner:
System.out.println(l[random.nextInt(30)]);
This is the question I've been assigned:
A so-called “star number”, s, is a number defined by the formula:
s = 6n(n-1) + 1
where n is the index of the star number.
Thus the first six (i.e. for n = 1, 2, 3, 4, 5 and 6) star numbers are: 1, 13, 37,
73, 121, 181
In contrast a so-called “triangle number”, t, is the sum of the numbers from 1 to n: t = 1 + 2 + … + (n-1) + n.
Thus the first six (i.e. for n = 1, 2, 3, 4, 5 and 6) triangle numbers are: 1, 3, 6, 10, 15, 21
Write a Java application that produces a list of all the values of type int that are both star number and triangle numbers.
When solving this problem you MUST write and use at least one function (such as isTriangeNumber() or isStarNumber()
or determineTriangeNumber() or determineStarNumber()). Also you MUST only use the formulas provided here to solve the problem.
tl;dr: Need to output values that are both Star Numbers and Triangle Numbers.
Unfortunately, I can only get the result to output the value '1' in an endless loop, even though I am incrementing by 1 in the while loop.
public class TriangularStars {
public static void main(String[] args) {
int n=1;
int starNumber = starNumber(n);
int triangleNumber = triangleNumber(n);
while ((starNumber<Integer.MAX_VALUE)&&(n<=Integer.MAX_VALUE))
{
if ((starNumber==triangleNumber)&& (starNumber<Integer.MAX_VALUE))
{
System.out.println(starNumber);
}
n++;
}
}
public static int starNumber( int n)
{
int starNumber;
starNumber= (((6*n)*(n-1))+1);
return starNumber;
}
public static int triangleNumber( int n)
{
int triangleNumber;
triangleNumber =+ n;
return triangleNumber;
}
}
Here's a skeleton. Finish the rest yourself:
Questions to ask yourself:
How do I make a Triangle number?
How do I know if something is a Star number?
Why do I only need to proceed until triangle is negative? How can triangle ever be negative?
Good luck!
public class TriangularStars {
private static final double ERROR = 1e-7;
public static void main(String args[]) {
int triangle = 0;
for (int i = 0; triangle >= 0; i++) {
triangle = determineTriangleNumber(i, triangle);
if (isStarNumber(triangle)) {
System.out.println(triangle);
}
}
}
public static boolean isStarNumber(int possibleStar) {
double test = (possibleStar - 1) / 6.;
int reduce = (int) (test + ERROR);
if (Math.abs(test - reduce) > ERROR)
return false;
int sqrt = (int) (Math.sqrt(reduce) + ERROR);
return reduce == sqrt * (sqrt + 1);
}
public static int determineTriangleNumber(int i, int previous) {
return previous + i;
}
}
Output:
1
253
49141
9533161
1849384153
You need to add new calls to starNumber() and triangleNumber() inside the loop. You get the initial values but never re-call them with the updated n values.
As a first cut, I would put those calls immediatly following the n++, so
n++;
starNumber = starNumber(n);
triangleNumber = triangleNumber(n);
}
}
The question here is that "N" neednt be the same for both star and triangle numbers. So you can increase "n" when computing both star and triangle numbers, rather keep on increasing the triangle number as long as its less the current star number. Essentially you need to maintain two variable "n" and "m".
The first problem is that you only call the starNumber() method once, outside the loop. (And the same with triangleNumber().)
A secondary problem is that unless Integer.MAX_VALUE is a star number, your loop will run forever. The reason being that Java numerical operations overflow silently, so if your next star number would be bigger than Integer.MAX_VALUE, the result would just wrap around. You need to use longs to detect if a number is bigger than Integer.MAX_VALUE.
The third problem is that even if you put all the calls into the loop, it would only display star number/triangle number pairs that share the same n value. You need to have two indices in parallel, one for star number and another for triangle numbers and increment one or the other depending on which function returns the smaller number. So something along these lines:
while( starNumber and triangleNumber are both less than or equal to Integer.MAX_VALUE) {
while( starNumber < triangleNumber ) {
generate next starnumber;
}
while( triangleNumber < starNumber ) {
generate next triangle number;
}
if( starNumber == triangleNumber ) {
we've found a matching pair
}
}
And the fourth problem is that your triangleNumber() method is wrong, I wonder how it even compiles.
I think your methodology is flawed. You won't be able to directly make a method of isStarNumber(n) without, inside that method, testing every possible star number. I would take a slightly different approach: pre-computation.
first, find all the triangle numbers:
List<Integer> tris = new ArrayList<Integer>();
for(int i = 2, t = 1; t > 0; i++) { // loop ends after integer overflow
tris.add(t);
t += i; // compute the next triangle value
}
we can do the same for star numbers:
consider the following -
star(n) = 6*n*(n-1) + 1 = 6n^2 - 6n + 1
therefore, by extension
star(n + 1) = 6*(n+1)*n + 1 = 6n^2 + 6n +1
and, star(n + 1) - star(n - 1), with some algebra, is 12n
star(n+1) = star(n) + 12* n
This leads us to the following formula
List<Integer> stars = new ArrayList<Integer>();
for(int i = 1, s = 1; s > 0; i++) {
stars.add(s);
s += (12 * i);
}
The real question is... do we really need to search every number? The answer is no! We only need to search numbers that are actually one or the other. So we could easily use the numbers in the stars (18k of them) and find the ones of those that are also tris!
for(Integer star : stars) {
if(tris.contains(star))
System.out.println("Awesome! " + star + " is both star and tri!");
}
I hope this makes sense to you. For your own sake, don't blindly move these snippets into your code. Instead, learn why it does what it does, ask questions where you're not sure. (Hopefully this isn't due in two hours!)
And good luck with this assignment.
Here's something awesome that will return the first 4 but not the last one. I don't know why the last won't come out. Have fun with this :
class StarAndTri2 {
public static void main(String...args) {
final double q2 = Math.sqrt(2);
out(1);
int a = 1;
for(int i = 1; a > 0; i++) {
a += (12 * i);
if(x((int)(Math.sqrt(a)*q2))==a)out(a);
}
}
static int x(int q) { return (q*(q+1))/2; }
static void out(int i) {System.out.println("found: " + i);}
}