How to find largest sequence of numbers in a line? - java

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

Related

How do I write a program to find 0's and 1's in Java?

I want it to take 10 values from the keyboard and find out if any of the 10 inputs contain 0 or 1 and if so, What position is in the array?
example
Input = 9 15 91 1 0 22 31 67 88 33
output = 4 found number 1, at position 2 3 4 7
1 found number 0, at position 5
5 found others, at position 1 6 8 9 10
I can't write any further because I still don't understand. Advise me please
I tried to write it but the output is still not correct.
public static int SequentialSearch(int number[], int key_1, int key_0) {
int looker;
for (looker = 0; looker < number.length; looker++) {
if (number[looker] == key_1)
return looker;
if (number[looker] == key_0)
return looker;
}
return -1;
}
public static void Loopcheck(int number[]) {
int key_1, key_0, others_key;
for (int count_check = 0; count_check < number.length; count_check++) {
if (number[count_check] / 10 == 1 || number[count_check] % 10 == 1) {
key_1 = 1;
break;
} else if (number[count_check] / 10 == 0 || number[count_check] % 10 == 0) {
key_0 = 0;
break;
}
}
}
public static int Print(int number[], int location) {
for (int loop = 0; loop < number.length; loop++)
if (location > -1)
System.out.print(" 0 : " + location);
return 0;
}
public static void main(String[] args) {
Scanner Sc = new Scanner(System.in);
int value1, value0, location, key1;
int[] number = new int[10];
for (int count = 0; count < number.length; count++) {
number[count] = Sc.nextInt();
}
int item1 = 1;
int item0 = 0;
location = SequentialSearch(number, item1, item0);
Loopcheck(number);
Print(number, item1);
}
}
you can use a method like this,
public void haszero(int numbers[])
{
int position;
for(position = 0; position < numbers.size; position++)
{
while(numbers[position] > 0)
{
if(numbers[position] % 10 == 0)
system.out.print("0 at " position)
number=number/10;
}
}
}
and then you can use same method as this for 1.
or the you can also do something like this
for(int position = 0; position < array.size; position++)
{
if (String.valueOf(array[position]).contains("0"))
system.out.print("0 at " position);
}
Since you are looking for a specific character, I would recommend working on String or char array instead. Some code you can consider that will probably give you an idea how to solve a problem:
//part 1
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
System.out.print("Enter first number- ");
int a= sc.nextInt();
System.out.print("Enter second number- ");
int b= sc.nextInt();
System.out.print("Enter third number- ");
int c= sc.nextInt();
// part 2
String Input = String.join(" ",Integer.toString(a),Integer.toString(b),Integer.toString(c));
System.out.println(Input);
// part 3
int i = 0;
while(i<Input.length()){
if(Input.charAt(i)=='0') System.out.println(String.join(" ","0 at position",Integer.toString(i+1)));
if(Input.charAt(i)=='1') System.out.println(String.join(" ","1 at position",Integer.toString(i+1)));
i++;
}
The most impactful advice I would provide is:
store your input as string or char[] instead of int[].
To solve: Create a collection(like a list, or array) to hold your valid indexes, and iterate through your input one letter at a time, adding valid indexes to your collection as they satisfy your condition. Implement a 'PrettyPrint()' that converts your collection into a nice output.
I went ahead a coded a solution that used int arrays. Here are the test results from one of my later tests.
Type 10 values: 0 1 2 3 4 5 6 7 8 9
1 found number 1, at position 2
1 found number 0, at position 1
8 found others, at position 3 4 5 6 7 8 9 10
Type 10 values: 12 23 34 45 127 21 84 0 73 364
3 found number 1, at position 1 5 6
1 found number 0, at position 8
6 found others, at position 2 3 4 7 9 10
Type 10 values:
To exit the program, you just press the Enter key.
My process was to maintain three int arrays. One held the indexes of all the ones. One held the indexes of all the zeros. One held the indexes of all the other values.
I wrote this code step by step, testing each step along the way. I probably ran two or three dozen tests, each testing one small part of the code.
The first thing I did was to get the input loop working correctly. I didn't test for non-numeric input, but that test could be added easily. I didn't limit the input to 10 numbers either. You can type 15 or 20 numbers if you want. Finally, I didn't limit the input to two-digit numbers. The code that looks for a digit should work for any positive integer value.
Next, I wrote a method to determine whether a number contained a particular digit. The method works with any digit, not just zero or one.
After that, it was a matter of getting the output to look correct.
Here's the complete runnable code.
import java.util.Scanner;
public class ZeroAndOne {
public static void main(String[] args) {
new ZeroAndOne().processInput();
}
public void processInput() {
Scanner scanner = new Scanner(System.in);
String line;
do {
System.out.print("Type 10 values: ");
line = scanner.nextLine().trim();
String[] parts = line.split("\\s+");
if (!line.isEmpty()) {
int[] input = new int[parts.length];
for (int index = 0; index < parts.length; index++) {
input[index] = Integer.valueOf(parts[index]);
}
System.out.println(processArray(input));
}
} while (!line.isEmpty());
scanner.close();
}
private String processArray(int[] input) {
int[] zeros = new int[input.length];
int[] ones = new int[input.length];
int[] other = new int[input.length];
int zeroIndex = 0;
int oneIndex = 0;
int otherIndex = 0;
for (int index = 0; index < input.length; index++) {
boolean isOther = true;
if (isDigit(input[index], 0)) {
zeros[zeroIndex++] = index;
isOther = false;
}
if (isDigit(input[index], 1)) {
ones[oneIndex++] = index;
isOther = false;
}
if (isOther) {
other[otherIndex++] = index;
}
}
StringBuilder builder = new StringBuilder();
builder.append(oneIndex);
builder.append(" found number 1, at position ");
builder.append(appendIndexes(ones, oneIndex));
builder.append(System.lineSeparator());
builder.append(zeroIndex);
builder.append(" found number 0, at position ");
builder.append(appendIndexes(zeros, zeroIndex));
builder.append(System.lineSeparator());
builder.append(otherIndex);
builder.append(" found others, at position ");
builder.append(appendIndexes(other, otherIndex));
builder.append(System.lineSeparator());
return builder.toString();
}
private boolean isDigit(int value, int digit) {
if (value == 0 && digit == 0) {
return true;
}
while (value > 0) {
int temp = value / 10;
int remainder = value % 10;
if (remainder == digit) {
return true;
}
value = temp;
}
return false;
}
private StringBuilder appendIndexes(int[] array, int length) {
StringBuilder builder = new StringBuilder();
for (int index = 0; index < length; index++) {
builder.append(array[index] + 1);
if (index < (length - 1)) {
builder.append(" ");
}
}
return builder;
}
}
Assuming that your input is a line containing integer numbers separated by space, you could read them all and then loop the String items via:
String input = Sc.readLine().split(" ");
int positions[] = new int[input.length];
int zeros = 0;
String zeroString = "";
int ones = 0;
String oneString = "";
int others = 0;
String otherString = "";
for (String item : input) {
boolean isOther = true;
String appendix = " " + item;
if (item.indexOf("0") >= 0) {
isOther = false;
zeros++;
zeroString += appendix;
}
if (item.indexOf("1") >= 0) {
isOther = false;
ones++;
oneString += appendix;
}
if (isOther) {
others++;
otherString += appendix;
}
}
System.out.println(ones + " found number 1, at position " + oneString);
System.out.println(zeros + " found number 0, at position " + zeroString);
System.out.println(others + " found others, at position " + otherString);

Lucky number with User Input

I'm facing troubles solving the following question: I suppose to get the user to input a number and check if it is a lucky number. A lucky number is the sum of squares of even-positioned digit (starting from the second position) is a multiple of 7.
Following is the example of my codes, when i run the program it will stuck at user input, please advise how do i get it to run:
public class Tester {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input a number: ");
int number = scanner.nextInt();
int count = 0;
while(number!=0) {
number/=10;
++count;
}
int[] array = new int[count];
int sum = 0;
for (int i=0; i<count; i++) {
array[i] = scanner.nextInt();
}
for (int i=0; i<count; i++) {
if(array[i]%2==0) {
sum+=(array[i]*array[i]);
}
else {
continue;
}
}
if (sum%7==0) {
System.out.println("The number: " +number+ "is a Lucky number");
}
else {
System.out.println("Oops! Not a Lucky number");
}
scanner.close();
}
}
I believe the culprit is the below loop:
for (int i=0; i<count; i++) {
array[i] = scanner.nextInt();
}
I think your intention was to get each of the digits into an array. However, you are getting an input from the scanner (which in this case is the user input) for count number of times.
While there are several ways of getting the number of digits and each digit into an array. I'm going to give you two ways. Also, I see no validations on the input integer (such as negative numbers, etc.) and I am going to ignore them right now.
Approach 1: Your for loop corrected
You just get the ith digit of the number using a formula.
for (int i=1; i<=count; i++) {
array[i] = (int) (number / Math.pow(10, count-i)) % 10;
}
Approach 2: Converting the numbers to String and back using streams
List<Integer> digits = Arrays.toStream(number.toString().split("")).map(
digitChar -> Integer.parseInt(digitChar)
).collect(Collectors.toList());
Note:
You need to import the classes java.util.Arrays and java.util.stream.Collectors
If you want even positioned digits,then you can directly get it in while loop.
while(number!=0) {
if(count%2 !=0){
int value = number %10; // even positioned values
// Do whatever you need to do with this value
}
number/=10;
++count;
}
If you want to convert the number into an digit array,then first find number of digits using log function and then store it array in reverse order.
int noOfDigits =(int) Math.floor(Math.log10(number)+1); // Finding No of digits
int[] array = new int[noOfDigits];
while(--noOfDigits>=0){
array[noOfDigits] = number/10; // storing every digits in reverse order
number%=10;
}
I don't know below code will be helpful for your core logic,yet I record this too.
If you want Sum of Squares of even positioned digits in number which is represented as array, then you can use below code.
int sum = 0;
for (int i=1; i<array.length; i+=2) {
sum += array[i] * array[i];
}
if (sum%7==0) {
// print number is lucky
}
else {
// print number is not lucky
}
If I understand your description correctly, here's a program that does what you want:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Input a number: ");
System.out.flush();
int number = scanner.nextInt();
int count = 0;
int n = number;
int sum = 0;
while(n!=0) {
int d = n % 10;
n/=10;
++count;
if (count % 2 == 0) {
System.out.printf("sum = %d + %d^2 = %d\n", sum, d, sum + d * d);
sum += d * d;
}
}
if (sum%7==0) {
System.out.printf("The number: %d is a Lucky number (%d = 7 * %d)", number, sum, sum / 7);
}
else {
System.out.println("Oops! Not a Lucky number");
}
scanner.close();
}
A lucky result:
Input a number: 123456
sum = 0 + 5^2 = 25
sum = 25 + 3^2 = 34
sum = 34 + 1^2 = 35
The number: 123456 is a Lucky number (35 = 7 * 5)

Generate 10 random no's and display the length of the longest increasing series in java without using array or anything

class IncreasingSeries {
public static void main(String args[]) {
int no, i, max = 0, counter = 0, temp = 0;
System.out.println("Generated values are : ");
//Random Numbers are generated and checked.
for (i = 1; i <= 10; i++) {
no = (int)(Math.random() * 100);
System.out.print(no + " ");
if (no > max) {
max = no;
counter++;
} else {
if (temp < counter) temp = counter;
max = 0;
counter = 1;
}
}
if (counter >= temp) System.out.println("\n The length of the longest increasing series is " + counter);
else System.out.println("\n The length of the longest increasing series is " + temp);
}
}
In some of the values the answers is correct but for some values the output is 1 more the actual answer.
for ex:
99,87,25,6,57,29,40,29,4,37. The output should be 2.
The problem lies at the place where you reset max. When you see a number that is lower than the current max, you should set it as the current max and then reset the counter:
else {
if(temp<counter)
temp=counter;
max=no; // <-- this line is changed!
counter=1;
}
To do this you can use the following code, which using three variables to track the state. The random number r is checked against the last number generated and if it is greater than or equal to the last random, increaseCount is incremented by 1. We also use another variable maxIncrease to store the maximum out of all increaseCount streaks. If the random number is less than the last number, we reset increase count.
int maxIncrease = 0;
int increaseCount = 0;
int last = 0;
for (int i = 0; i < 10; i++) {
int r = (int) (Math.random() * 1000);
System.out.println(r);
if (r >= last) {
increaseCount++;
if(increaseCount > maxIncrease)
maxIncrease = increaseCount;
last = r;
} else {
increaseCount = 0;
}
}
System.out.println("Max streak was: " + maxIncrease);

array called peopleTypes that can store a maximum of 50 integer values. enter a series of 1,2,3,4 and output how many of each number was inputed

import java.util.Scanner;
public class People
{
public static final Scanner keyboard = new Scanner(System.in);
static final int Max= 50;
public static void main(String[]args)
{
int index;
int check;
int infants = 0, children = 0, teens = 0, adults = 0;
System.out.println("Please enter value:");
int [] peopleTypes = new int[Max];
for(index=0; index<Max; index++)
{
peopleTypes[index] = keyboard.nextInt();
if(peopleTypes[index] == 1)
infants = infants + 1;
if(peopleTypes[index] == 2)
children = children + 1;
if(peopleTypes[index] == 3)
teens = teens + 1;
if(peopleTypes[index] == 4)
adults = adults + 1;
else
index = index-1;
System.out.print("");
}
So basically I have to create a code that allows a user to input 50 values (1,2,3,4) into a array and count how many of each was inputted and outputs that. I am stuck on creating the code to count the inputted values. I am new to array and am not sure if I'm on the right path.
Actually you don't need to store the input, take a (closer) look at a possible solution:
import java.util.Scanner;
public class People {
static final Scanner keyboard = new Scanner(System.in);
static final int MAX = 50;
static final String[] LABLES = {"infants", "children", "teens", "adults"};
public static void main(String[] args) {
int[] counts = new int[4];
for (int i = 0; i < MAX; i++) {
System.out.println("Please enter value:");
int current = keyboard.nextInt(); //problem input: "abc" -> java.util.InputMismatchException
while (current > 4 || current < 1) {//checks range
System.out.println("Please enter a valid value (between 1 and 4):");
current = keyboard.nextInt();//...and repeat
}
counts[current - 1]++;//increment counter, "current - 1", since 0-based array and 1-based input
}
System.out.println("Evaluation finished!");
for (int i = 0; i < 4; i++) {//print the output
System.out.println(LABLES[i] + ": " + counts[i]);
}
}
}
I maybe misunderstanding the context but I do not see the need for creating a peopleTypesArray. My understanding is that all you need is a count or teens , adults etc from a list of 50 people, so just keep incrementing the individual counters and display them outside the loop. Something like:
for(int i = 0 ; i < 50; i++){
int peopleType = keyBoard.nextInt();
if(peopleType == 0){
infantCount++;
}
---- and so on
}
System.ou.println(" infant = " + infantCount);
--- and so on

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 :)

Categories

Resources