Number of times 3 is rolled - java

import java.util.Random;
public class RollingDice {
public static void main(String[] args){
int numSides = 6;
Random ranGen = new Random();
for (int i =1; i <= 20; i++){
if (ranGen.nextInt(numSides) == 3) {
System.out.println("A 3 has been rolled!");
}
}}}
this is my code so far. It prints the message every time the number 3 is rolled. I am new to coding, so please bear with me. What i want to do next is store the numbers of times 3 is rolled so when the loop exits, it displays the final count of the number of times 3 was actually rolled in that process. That making the end result be some number which represents the number of times the number 3 was rolled by the system.
Thanks!
-Sail

Define a count.
int count = 0;
Increase count each time you encounter a roll of 3. Inside of the loop, if you roll a 3:
count = count + 1;
Print count outside of the loop.
System.out.printf("A 3 was been rolled %d times.\n", count);

Random ranGen = new Random();
int numberOfThrees = 0;
for (int i =1; i <= 20; i++){
if (ranGen.nextInt(numSides) == 3) {
++numberOfThrees;
}
}
System.out.println(numberOfThrees);

Like this:
import java.util.Random;
public class RollingDice {
public static void main(String[] args){
int numSides = 6;
int threes = 0;
Random ranGen = new Random();
for (int i =1; i <= 20; i++) {
if (ranGen.nextInt(numSides) == 3) {
System.out.println("A 3 has been rolled!");
threes++
}
}
System.out.println("A 3 has been rolled " + threes + " times!");
}}
Actually, what you are recording is the number of 4's that have been rolled, since nextInt returns a number between 0 and 5.

You could simply have a counter
import java.util.Random;
public class RollingDice {
public static void main(String[] args){
int numSides = 6;
int cnt = 0; // <-- Declare a counter
Random ranGen = new Random();
for (int i =1; i <= 20; i++){
if (ranGen.nextInt(numSides) == 3) {
System.out.println("A 3 has been rolled!");
cnt++; // <-- increment counter
}
}
System.out.printf("A 3 has been rolled %d times!\n", cnt);
}

Related

Error in Coding problem. Everything is Written But Nothing Prints

Nothing will print when run. Where's the error?
In this project you will simulate two games. In the first game, roll one die four times and record a "win" if a six is rolled at least once during the four rolls, otherwise record a "loss". In the second game, roll two die twenty-four times and record a "win" if two six's are rolled at least once during the twenty-four rolls, otherwise record a "loss". Your program should simulate running each game a million times and output the number of wins and losses for each game.
import java.util.Random;
public class Driver {
public static void main(String[] args) {
int win6 = 0;
int lose6 = 0;
int win24 = 0;
int lose24 = 0;
int n = 100000000;
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= 4; j++){
Random r = new Random();
int next = r.nextInt(1-6);
if (next == 6){
win6 = win6 + 1;
break;
}
}
lose6 = 100000000 - win6;
for (int u = 0; u <= 24; u++){
Random r = new Random();
Random t = new Random();
int next1 = r.nextInt(1-6);
int next2 = t.nextInt(1-6);
if (next1 == 6 && next2 == 6){
win24 = win24 + 1;
break;
}
}
lose24 = 100000000 - win24;
}
System.out.println(win6);
System.out.println(lose6);
System.out.println(win24);
System.out.println(lose24);
}
}

How to find largest sequence of numbers in a line?

I have a class assignment where we have to use Math.random to generate values of 0 or 1 representing heads and tails respectively. The point of the program is to have the user input the number of times the coin is flipped, and the program then spits out a string of random 0s and 1s representing the flips. The program then has to find and state the longest number of heads in a row.
eg.
(heads = 0 / tails = 1)
number of tosses: 10
result: 0001100100
longest sequence of heads: 3
this is what I have so far:
import java.util.Scanner;
import java.lang.Math;
public class CoinFlip
{
public static void main(String args[])
{
int Toss; // State variable for tosses
int Heads; // State variable for # of heads
System.out.println("Enter number of tosses:");
Scanner input1 = new Scanner(System.in);
Toss = input1.nextInt();
for(int i = 0; i < Toss ; i++)
{
int Coin = (int) (Math.random() + .5);
System.out.print(Coin); // Prints sequence of flips
}
System.out.println("");
System.out.println("Longest sequence of heads is "); // Says largest sequence of heads
}
}
I'm stuck as to how I read the sequence and then display the longest consecutive head count.
I have written a function to do this. I take the String that you were printing and made a String out of it. I pass this string as a parameter to the function and count the consecutive 0 in it.
This is the code for the same:
import java.util.Scanner;
public class CoinFlip {
public static void main(String args[]) {
int Toss; // State variable for tosses
System.out.println("Enter number of tosses:");
Scanner input1 = new Scanner(System.in);
Toss = input1.nextInt();
StringBuffer coinSequenceBuffer = new StringBuffer(Toss);
for (int i = 0; i < Toss; i++) {
int Coin = (int) (Math.random() + .5);
System.out.print(Coin); // Prints sequence of flips
coinSequenceBuffer.append(Coin);
}
String coinSequence = coinSequenceBuffer.toString();
System.out.println("");
int numberOfConsecutiveHead = findNumberOfConsecutiveHead(coinSequence);
System.out.println("Longest sequence of heads is " + numberOfConsecutiveHead);
}
private static int findNumberOfConsecutiveHead(String coinSequence) {
int count = 1;
int max = 0;
// Starting loop from 1 since we want to compare it with the char at index 0
for (int i = 1; i < coinSequence.length(); i++) {
if (coinSequence.charAt(i) == '1') {
// Since we are not intersted in counting 1's as per the question
continue;
}
if (coinSequence.charAt(i) == coinSequence.charAt(i - 1)) {
count++;
} else {
if (count > max) { // Record current run length, is it the maximum?
max = count;
}
count = 1; // Reset the count
}
}
if (count > max) {
max = count;
}
return max;
}
}
I have tried adding comments so that you can easily understand it. Let me know if you face any issue in understanding it.
This is pretty simple. Just count zeros and reset counter when not zero.
public static void main(String... args) {
System.out.print("Enter number of tosses: ");
int[] arr = new int[new Scanner(System.in).nextInt()];
Random random = new Random();
for (int i = 0; i < arr.length; i++)
arr[i] = random.nextInt(2);
System.out.println(Arrays.toString(arr));
System.out.println("Longest sequence of heads is " + findLongestZeroSequence(arr));
}
public static int findLongestZeroSequence(int... arr) {
int res = 0;
for (int i = 0, cur = 0; i < arr.length; i++) {
if (arr[i] == 0)
res = Math.max(res, ++cur);
else
cur = 0;
}
return res;
}
Here's my go at it:
class CoinFlip {
public static void main(String args[])
{
// Get number of tosses from user
System.out.print("Enter number of tosses: ");
System.out.flush();
Scanner input1 = new Scanner(System.in);
int toss = input1.nextInt();
// Build a string of random '0's and '1's of the specified length (number of tosses)
StringBuilder sb = new StringBuilder();
for(int i = 0; i < toss ; i++)
{
long coin = Math.round(Math.random());
sb.append(coin == 0? '0' : '1');
}
String seq = sb.toString();
// Print the generated String
System.out.println(seq);
// Walk through the string tallying up runs of heads
int count = 0;
int max = 0;
for (int i = 0 ; i < seq.length() ; i++) {
if (seq.charAt(i) == '0') {
count += 1;
} else {
if (count > max)
max = count;
count = 0;
}
}
// Gotta check at the end to see if the longest sequence of heads
// was at the end of the string
if (count > max)
max = count;
// Print the length of the longest sequence
System.out.println("Longest sequence of heads is " + max);
}
}
Sample run:
Enter number of tosses: 40
1000001000000010010101011000011100001000
Longest sequence of heads is 7
Explanations after the code.
import java.util.Scanner;
public class CoinFlip {
private static final int HEADS = 0;
private static final int TAILS = 1;
public static void main(String[] args) {
Scanner input1 = new Scanner(System.in);
System.out.print("Enter number of tosses: ");
int toss = input1.nextInt();
int count = 0;
int longest = 0;
StringBuilder sb = new StringBuilder(toss);
for (int i = 0; i < toss; i++) {
int coin = (int) ((Math.random() * 10) % 2);
sb.append(coin);
System.out.printf("Got %d [%s]%n", coin, (coin == HEADS ? "HEADS" : "TAILS"));
if (coin == HEADS) {
count++;
System.out.println("count = " + count);
}
else {
if (count > longest) {
longest = count;
System.out.println("longest = " + longest);
}
count = 0;
}
}
if (count > longest) {
longest = count;
System.out.println("longest = " + longest);
}
System.out.println(sb);
System.out.print("Longest sequence of heads is " + longest);
}
}
In order to generate a random number which must be either 0 (zero) or 1 (one), I call method random() of class java.lang.Math. The method returns a double between 0.0 and 1.0. Multiplying by ten and then performing modulo 2 operation on that number returns either 0.0 or 1.0 which is a double and therefore needs to be cast to an int.
Each time the above calculation returns 0 (zero) I increment a count. If the calculation returns 1 (one) then I check whether the count is greater than longest and update longest accordingly, after which I reset the count back to zero.
Note that if the last toss is "heads" then the check for the longest sequence will not be performed. Hence I repeat the check for the longest sequence after the for loop.
At the end of the for loop, I have all the required information, i.e. the string that records all the results of all the coin tosses plus the longest sequence of heads.
Here is sample output:
Enter number of tosses: 10
Got 1 [TAILS]
Got 1 [TAILS]
Got 1 [TAILS]
Got 0 [HEADS]
count = 1
Got 1 [TAILS]
longest = 1
Got 0 [HEADS]
count = 1
Got 0 [HEADS]
count = 2
Got 1 [TAILS]
longest = 2
Got 0 [HEADS]
count = 1
Got 0 [HEADS]
count = 2
1110100100
Longest sequence of heads is 2

3 quick for-loop integer homework problems

Have some loops homework to do, and need some help! Here are the 3 questions:
Us the method below to take two integers and only output numbers divisible by ten. Make the list start with the largest of the numbers.
public static void divisibleByTen( int start, int end )
The above method is the example on the HW sheet. I have no idea how to implement it. I also don't know how to start with the largest number. Right now, I don't know how to take user input into the loop, so I made an example with 10 and 100:
public class QuestionOne {
public static void main(String [] args) {
for (int i = 10; i <= 100; i += 10){
System.out.println(i + "");
}
}
}
Use the method below to output the triangle below. Assume the positive number is between 3 and 9.
public static void printLeftUpper( int num)
Desired output is this number triangle:
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Here's my code so far:
public class QuestionTwo {
public static void main(String [] args) {
for(int i = 5; i >= 1; i--) {
for(int j = 1; j <= i; ++j) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
The third question I have ZERO idea how to start.
3. public static void sumEvens( int begin, int end )
Use the method above to take in two numbers, called begin and end, inclusive, checks if the numbers between them are even. Include the numbers in the sum if they are even as well, and print out the sum of all such numbers.
Example: sumEven(16, 11) uses 16+14+12 = 42, and outputs "For numbers between 16 and 11, the sum of all even numbers is 42."
The help is GREATLY appreciated. Thanks so much!!
Who likes homework? I've taken the liberty of doing Question 3, hope that helps!
import java.util.List;
import java.util.ArrayList;
public class OddEven {
public static void main(String[] args) {
sumEvens(0,1000);
}
// Gets sum of odd and even numbers between a given range:
public static void sumEvens(int begin, int end)
{
List<Integer> evenNumbers = new ArrayList<Integer>();
List<Integer> oddNumbers = new ArrayList<Integer>();
if (begin < end)
{
for (int i = begin; i <= end; i++)
{
// Number is even:
if (i % 2 == 0)
{
evenNumbers.add(i);
}
// Number is odd:
else
{
oddNumbers.add(i);
}
}
}
else
{
for (int i = begin; i >= end; i--)
{
// Number is even:
if (i % 2 == 0)
{
evenNumbers.add(i);
}
// Number is odd:
else
{
oddNumbers.add(i);
}
}
}
// Calculate even values:
int evenSum = 0;
for (int i: evenNumbers) {
evenSum += i;
}
System.out.println("The sum of all even numbers is: " + evenSum);
// Calculate odd values:
int oddSum = 0;
for (int i: oddNumbers) {
oddSum += i;
}
System.out.println("The sum of all odd numbers is: " + oddSum);
}
}
public class QuestionOne {
public static void main(String [] args) {
divisibleByTen( 1, 100 );
}
public static void divisibleByTen( int start, int end ){
// reversal big to small (100 to 1)
for(int i = end; i >= start; i--){
// use mod (%) to check if i is divisible by 10
if( i%10 == 0 ){
// it is then output
System.out.println(i);
}
}
}
}
Question 2 is correct.
Question 3
public static void main(String [] args) {
sumEvens( 16, 10);
}
public static void sumEvens( int begin, int end ){
int start = 0;
int last = end;
int sum = 0;
if(begin > end){
start = end;
end = begin;
}else{
start = begin;
}
for(int i = start; i <= end; i++){
// get even integers
if(i%2 == 0){
sum += i;
}
}
System.out.println("For numbers between " +begin+ " and " +last+ ", the sum of all even numbers is " +sum);
}

Random Coin Flipper output number of times run

I am attempting to write a program in java that flips an imaginary coin and outputs the flips and then when a certain side has been flipped 3 times, it stops and tells you the number of times it flipped. My program doesn't seem to be working
My code is below:
import java.util.*;
public class FlipperThree {
public static void main(String[] args) {
boolean fin = false;
while(!fin){
System.out.println("Welcome to Flipper!");
int h = 0;
int hcount = 0;
int tcount = 0;
int ocount = 0;
String random;
String[] ht;
boolean done = false;
while(!done){
for(hcount<3||tcount<3){ht = new String[] {"Heads","Tails"};
Random r =new Random();
random = ht[r.nextInt(ht.length)];
System.out.println(random);
}
if (hcount!=3||tcount!=3){
if(random == ht[h]){
hcount++;
ocount++;
tcount = 0;
}else{
hcount = 0;
tcount++;
ocount++;
}
}else{
System.out.println("BINGO!That only took " + ocount+" flips to get 3 in a row!");
done = true;
}
}
}fin = true;
}
}
In general your program is much more complicated than necessary. You only need a single loop
You were using == to compare strings. Instead of random == ht[h] you should say random.equals(ht[h])
Instead of looping while either heads or tail counts are less than 3, you only want to keep looping while both are less than three. So instead of hcount!=3 || tcount!=3 it's hcount!=3 && tcount!=3
.
public class FlipperThree {
public static void main(String[] args) {
System.out.println("Welcome to Flipper!");
int h = 0;
int hcount = 0;
int tcount = 0;
int ocount = 0;
String[] ht = new String[] {"Heads","Tails"};
Random r =new Random();
while (hcount < 3 && tcount < 3) {
String random = ht[r.nextInt(ht.length)];
System.out.println(random);
if(random.equals(ht[h])){
hcount++;
ocount++;
tcount = 0;
}
else{
hcount = 0;
tcount++;
ocount++;
}
}
System.out.println("BINGO!That only took " + ocount+" flips to get 3 in a row!");
}
}
$ java FlipperThree
Welcome to Flipper!
Tails
Heads
Heads
Tails
Heads
Heads
Tails
Tails
Tails
BINGO!That only took 9 flips to get 3 in a row!
Remove the for and init ht once and remove your first while too and change || to &&:
import java.util.*;
public class FlipperThree {
public static void main(String[] args) {
System.out.println("Welcome to Flipper!");
int h = 0;
int hcount = 0;
int tcount = 0;
int ocount = 0;
String random;
String[] ht = new String[] {"Heads","Tails"};
boolean done = false;
while(!done){
Random r =new Random();
random = ht[r.nextInt(ht.length)];
System.out.println(random);
if (hcount!=3 && tcount!=3){
ocount++;
if(random == ht[h]){
hcount++;
tcount = 0;
}else{
hcount = 0;
tcount++;
}
}else{
System.out.println("BINGO!That only took " + ocount+" flips to get 3 in a row!");
done = true;
}
}
}
You can achieve this with much simpler code when you realize that you just need to keep track of the number of consecutive coin faces. It doesn't matter what face it is:
/**
* return:
* the number of coin tosses until you get the same face n consecutive times
*/
static int numTossesUntilNConsecutiveFaces(int n) {
Random toss = new Random();
// This counts the number of consecutive faces following a given face
// For example:
// for sequence 1 0, numConsecutive == 0
// for sequence 1 1, numConsecutive == 1
// for sequence 0 0 0, numConsecutive == 2
int numConsecutives = 0;
int numTosses = 0;
// Initialize the lastCoin value as -1, so the first coin won't be equal to it
int lastCoin = -1;
do {
// The result of the toss will be 0 or 1 (head or tails)
int coin = toss.nextInt(2);
if (coin == lastCoin) {
// If the current coin is the same as the last coin, increment the counter
numConsecutives++;
} else {
// If it is different, reset the counter
numConsecutives = 0;
}
// Make this coin the last coin
lastCoin = coin;
numTosses++;
// Stop when the number of consecutives is n - 1.
// For n == 3, that is when the last three numbers were 1 1 1 or 0 0 0
} while (numConsecutives < n - 1);
return numTosses;
}
Then you just need to call:
int tosses = numTossesUntilNConsecutiveFaces(3);
public class FlipperThree {
public static void main(String[] args) {
System.out.println("Welcome to Flipper!");
int previousFlip = -1;
int continuousFlip = 0;
int totalFlips = 0;
String[] ht = new String[] {"Heads","Tails"};
Random r = new Random();
while (continuousFlip < 3) {
int r = r.nextInt(ht.length);
totalFlips++;
System.out.println(ht[r]);
if(previousFlip == r){
continuousFlip++
} else {
continuousFlip = 1;
previousFlip = r;
}
}
System.out.println("BINGO!That only took " + totalFlips +" flips to get 3 in a row!");
}
}
Just wanted to show a shorter version. Whole point is that you don't need to keep track of BOTH the heads or tails, you just need to keep track of how much you've flipped the same number consequtively. Very minor optimization concerning real world performance, but still an improvement :)

For loop with error in code

UPDATE****
I have my program compiling and executing correctly but now I have faced another problem. I need to create variables that will count each time a certain random number is generated. For example count0 is supposed to record how many times the integer 0 is generated. This is what I have:
import java.util.Random;
public class L10{
public static void main(String[] args){
int total = 100;
Random randObj = new Random();
final int UPPER_BOUND = 10;
for (int i=0; i < total; i++){
int randomInt = randObj.nextInt(UPPER_BOUND);
System.out.print("\n" + randomInt);
int count0 = 0;
if(randomInt==0){
System.out.print(randomInt + count0);
}
int count1 = 1;
if(randomInt==1){
}
int count2 = 2;
int count3 = 3;
int count4 = 4;
int count5 = 5;
int count6 = 6;
int count7 = 7;
int count8 = 8;
int count9 = 9;
}
}
}
The output shows the random number, in this case zero, and prints a zero next to it. I'm not exactly sure how to write code that keeps track of how many times zero is generated. Any suggestions?
Try this:
import java.util.Random;
public class HelloWorld{
public static void main(String []args){
Random randObj = new Random();
final int UPPER_BOUND = 10;
int total = 100;
String star = "*";
for (int i=0; i < UPPER_BOUND; i++){
int randomInt = randObj.nextInt(total);
System.out.print(randomInt);
}
}
}
Modifications:
Random randObj = new Random();
int randomInt = randObj.nextInt(total);
I think your intention is to generate 100 random integers in the range 0-9, and count the frequency of each.
Using separate variables for each count is a poor idea. A better idea is to use a single array of size 10, whose index is the random number.
Modifying your code:
public static void main(String[] args){
final int TOTAL = 100, UPPER_BOUND = 10;
Random randObj = new Random();
int[] count = new int[UPPER_BOUND];
// collect frequencies
for (int i=0; i < TOTAL; i++)
count[randObj.nextInt(UPPER_BOUND)]++;
// report frequencies
for (int i=0; i < UPPER_BOUND; i++)
System.out.print(i + "'s frequency was " + count[i];
}
import java.util.Random;
public class L10{
public static void main(String[] args){
int total = 100;
int[] CountArray = new int[total]; //count numbers
Random randObj = new Random();
final int UPPER_BOUND = 10;
for (int i=0; i < total; i++){
int randomInt = randObj.nextInt(UPPER_BOUND);
System.out.print("\n" + randomInt);
switch(randomInt){
case(0):{
CountArray[0]++;
break;
}
case(1):{
CountArray[1]++;
break;
}
case(2):{
CountArray[2]++;
break;
}
case(3):{
CountArray[3]++;
break;
}
case(4):{
CountArray[4]++;
break;
}
case(5):{
CountArray[5]++;
break;
}
case(6):{
CountArray[6]++;
break;
}
case(7):{
CountArray[7]++;
break;
}
case(8):{
CountArray[8]++;
break;
}
case(9):{
CountArray[9]++;
break;
}
}
}
System.out.println("");
for(int j = 0;j<UPPER_BOUND;j++){
System.out.println("number of "+ j+" generated "+CountArray[j]);
}
}
}
This is the Code that I came up with. I used an array to count each element and used switch case to count them separately. so at the end of the for loop. I printed them. This way you can get the number of elements distinctively.
You are missing () after new Random.

Categories

Resources