coinFlip heads streak output - java

I'm supposed to flip a coin 100 times, and find out the longest streak of heads, then output it, but so far, it's only giving me how many heads there are in total. I've tried a bunch of things but can't find a solution.
public class LongestStreak extends ConsoleProgram
{
public static final int FLIPS = 100;
public void run()
{
int h = 0;
int t = 0;
boolean wasHeads = false;
boolean isHeads = false;
int streak = 0;
int ih = 0;
for (int i = 0; i < FLIPS; i++) {
int coinFlip = Randomizer.nextInt(1, 2);
if (coinFlip == 2) {
System.out.println("Heads");
h++;
ih++;
isHeads = true;
if (ih > 1) {
wasHeads = true;
}
if ((isHeads = true) && (wasHeads = true)) {
streak++;
} else {
streak = 0;
}
} else if (coinFlip == 1) {
System.out.println("Tails");
t++;
isHeads = false;
ih = 0;
}
}
System.out.println(streak);
}
}

You need to substantially simplify your code.
public class LongestStreak extends ConsoleProgram
{
public static final int FLIPS = 100;
public void run()
{
int wasHeads = 0;
int streak = 0;
int bestStreak = 0;
for (int i = 0; i < FLIPS; i++) {
int coinFlip = Randomizer.nextInt(1, 2);
if (coinFlip == 2) {
streak++;
wasHeads = 1;
} else if (coinFlip == 1) {
wasHeads = 0;
if (steak > bestStreak) {
bestStreak = streak;
}
streak = 0;
}
}
System.out.println(streak);
}
}
Reset streak when it ends (coinFlip is 1), but first check if it's better than your best streak before then, updating the bestStreak if so accordingly. Otherwise, just iterate streak and keep wasHeads at 1 for each head. Note there's not need for a boolean here; a 1 or 0 integer is literally and logically the same thing.

You can simplify your code a bit, wasHeads and isHeads are not really needed. Also, more descriptive variable names makes your code easier to understand. So, something like this:
public void run() {
int highestNumberOfConsecutiveHeads = 0;
int currentNumberOfConsecutiveHeads = 0;
for (int i = 0; i < 100; i++) {
if (Randomizer.nextInt(1, 2) == 2) {
currentNumberOfConsecutiveHeads++;
if (currentNumberOfConsecutiveHeads > largestNumberOfConsecutiveHeads) {
highestNumberOfConsecutiveHeads = currentNumberOfConsecutiveHeads;
}
} else {
currentNumberOfConsecutiveHeads = 0;
}
}
System.out.println("Longest streak: " + highestnumberOfConsecutiveHeads);
}

First and foremost, fix your line here so it's easier to read: }} else if (coinFlip == 1) {
(You need a newline between those two close braces)
I would consider setting up some more clear variable names. For example: totalHeads, totalTails. I'm not quite getting what your ih variable is SUPPOSED to be, but the variable names I would use for solving this problem are thisStreak and bestStreak. is/washeads should be unnecessary. I think that should be enough of a push to get you to a solution.

Thanks for the help, fixed my code :)
public class LongestStreak extends ConsoleProgram
{
public static final int FLIPS = 100;
public void run()
{
int h = 0;
int t = 0;
boolean wasHeads = false;
boolean isHeads = false;
int longest = 0;
int streak = 0;
int ih = 0;
for (int i = 0; i < FLIPS; i++) {
int coinFlip = Randomizer.nextInt(1, 2);
if (coinFlip == 2) { //heads
System.out.println("Heads");
if (wasHeads = true) {
streak++;
} else {
streak = 0;
}
wasHeads = true;
} else if(coinFlip == 1) { //tails
System.out.println("Tails");
t++;
isHeads = false;
if (streak > longest){
longest = streak;
}
streak = 0;
ih = 0;
}
}
System.out.println("Longest streak of heads: " + longest);
}
}

Related

Show certain amount of prime numbers

I have been working on some java code to show prime numbers . I have got as far as having it show all prime numbers between 0 and 100 .
How would I make it so that I could set a variable to say 20 and it would show me the first 20 prime numbers.
My Code :
public class PrimeNumber {
/**
* #param args the command line arguments
*/
private static boolean prime = true;
private static int count = 20;
public static void main(String[] args) {
for (int i = 2; i < 100; i++) {
for (int j = 2; j < 100; j++) {
if(i == j)
{
continue;
}
if (i % j == 0) {
prime = false;
break;
} else {
prime = true;
}
}
if (prime) {
System.out.println(i + " is a Prime:");
}
}
}
}
Here is the simplest possible implementation, for the OPs code.
Decrease the count variable and check it in the outer for loop till it reaches zero. Also Inner for-loop should check only till the current value of (i/2 + 1). The other half you can always skip, the value will will divide the number will be i itself.
public class PrimeNumber {
/**
* #param args the command line arguments
*/
private static boolean prime = true;
private static int count = 20;
public static void main(String[] args) {
for (int i = 2; count>0; i++) {
for (int j = 2; j < i/2 + 1; j++) {
if (i % j == 0) {
prime = false;
break;
} else {
prime = true;
}
}
if (prime) {
System.out.println(i + " is a Prime:");
count--;
}
}
}
}
Check below code for your answer:
public class PrimeNumber {
private static boolean prime = true;
private static int count = 20;
public static void main(String[] args) {
for (int i = 2; i < count+1; i++) {
for (int j = 2; j < 100; j++) {
if(i == j)
{
continue;
}
if (i % j == 0) {
prime = false;
break;
} else {
prime = true;
}
}
if (prime) {
System.out.println(i + " is a Prime:");
}}}}

Sudoku Solver Java

OK so I have programmed a Sudoku solver.. And when I run the debug to check if its going through everything.. it is.. But it does not seem to work. It will print it out, and it will change the "." to 0's. But thats as far as it goes. It will not change the 0's, to the numbers when it loops over it.
public class SudokuSolver {
int[][] sudoku;
String data;
public SudokuSolver()
{
getPuzzle();
solvePuzzle(0,0);
}
private void getPuzzle()
{
try
{
Scanner in = new Scanner(new File("C:/Users/Ben/workspace/Sudoku Solver/src/puzzle1.txt"));
sudoku = new int[9][9];
for(int y = 0; y<9;y++)
{
for(int x = 0; x<9; x++)
{
data = in.next();
if(data.equals("."))
sudoku[x][y]=0;
else
sudoku[x][y] = Integer.parseInt(data);
}
}
in.close();
}
catch(Exception e)
{
}
for(int y = 0; y<9; y++)
{
for(int x = 0; x<9; x++)
{
System.out.print(sudoku[x][y]);
if(x ==2 || x ==5)
System.out.print(" ");
if(x==8)
{
System.out.print("\n");
}
}
if(y == 2|| y == 5)
{
System.out.println(" ");
}
}
}
private boolean isValid(int x, int y, int num)
{
int xSection = x/3;
int ySection = y/3;
for ( int row = 0; row < sudoku.length; row++ )
{
if(sudoku[row][y] == num)
{
return false;
}
}
for( int col = 0; col < sudoku.length; col++)
{
if(sudoku[x][col] == num)
{
return false;
}
}
for(int box = 3*xSection; box < 3*xSection + 3; box++)
{
for(int boxY = 3*ySection; boxY < 3*ySection + 3; boxY++)
{
if(sudoku[box][boxY] == num)
{
return false;
}
}
}
return true;
}
private int xPosition(int x, int y)
{
if(x<8)
{
return x+1;
}
else
{
return 0;
}
}
private int yPosition(int x, int y)
{
if(x<8)
{
return y;
}
else
{
return y+1;
}
}
private boolean solvePuzzle(int x, int y)
{
if( x >= 9 || y >= 9)
{
return true;
}
else
{
for(int num = 1; num < 10; num++)
{
if(isValid(x,y,num))
{
sudoku[x][y] = num;
if( solvePuzzle(xPosition(x,y), yPosition(x,y)) )
{
return true;
}
else
{
sudoku[x][y] = 0;
}
}
}
return false;
}
}
public static void main(String args[])
{
SudokuSolver solver = new SudokuSolver();
}
}
You're printing the puzzle inside the getPuzzle-method, which is before solvePuzzle has been called. You need to print the puzzle after it has been solved.

Prime numbers loop returning blank string

public String primeNumbers()
{
//create variable to be returned
String prime = "";
int num = 0;
for(int i = 0; i < this.limit; i++)
{
num = this.limit - i;
for(int count = 2; count < this.limit; count++)
{
if ( num % count == 0)
{
count = this.limit + 1;
}
else if ( num == count)
{
prime += num + ", ";
}
}
}
return prime;
}
The goal of this is to produce a list of prime numbers in between 1 and the upper limit which is the private variable limit. However, when I run the code, I get a blank message as a return. Why is this?
I don't quite understand the logic of your code, but having helper methods is good.
public String primeNumbers()
{
//create variable to be returned
String prime = "";
for(int i = 0; i < this.limit; i++)
{
if(this.isPrime(i)){
prime += i + ", ";
}
}
return prime;
}
private boolean isPrime(int number){
if(number <= 1){
return false;
} else if(number == 2){
return true;
}
for(int i = 2; i < number; i++){
if(number%i == 0){
return false;
}
}
return true;
}
The isPrime() is naive, and can definitely be optimized.
There was a question about this yesterday and I ended up writing this as a refresher for myself.
public class Erasthotenes
{
private int range;
private boolean[] nums;
public Erasthotenes(int range)
{
this.range = range;
nums = new boolean[range];
for(int i = 0; i < nums.length; ++i)
{
nums[i] = true;
}
nums[0] = nums[1] = false;
}
public void sieve()
{
int root = (int) Math.sqrt(range);
for(int i = 2; i < root; ++i)
{
for(int j = i + 1; j < range; ++j)
{
if(j % i == 0)
{
nums[j] = false;
}
}
}
}
public void printPrimes()
{
for(int i = 0; i < nums.length; ++i)
{
if(nums[i] == true)
{
System.out.print(i + ", ");
}
}
}
}
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

Project Euler #3 Java

public class Problem3 {
public static void main (String args[]) {
System.out.print(primeMod(60085147514L));
}
public static double primeMod(long d) {
long max = 0;
int count = 0;
for (long i = 2; i < d; i++) {
if (d % i == 0) {
boolean isPrime = primeCounter(i);
if(isPrime == true) {
max = i;
System.out.println(max);
}
} else {
max = max;
}
}
return max;
}
public static boolean primeCounter(long x) {
int count = 0;
for (int s = 1; s <= x; s++) {
if (x % s == 0) {
count++;
}
}
if (count == 2) {
return true;
} else {
return false;
}
}
}
My program works for smaller numbers but it Throws an Arthmetic Exception for Divide by 0 when its not dividing by zero.please dont give me the answer,just wanna understand it and improve my skills
thank you
My guess would be that s is overflowing, leading eventually to a divide by zero. Make s a long instead.

Java - minimax algorithm issue

I'm working on a tictactoe board for practice making classes and i have ran into a problem with my algorithm. it seems to be returning the best move offensive, but it doesn't play defense. i dont know where i have messed up and cant seem to find it. i have looked over a lot of things on here about it and ive compared it to simular projects, but still can't seem to get it. here is my code.
package TicTacToe;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Solution {
private static GameBoard currentBoard;
private static Player botPlayer;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String player;
System.out.println("ENTER bot: ");
player = in.next();
if(player.equalsIgnoreCase("X")) {
botPlayer = Player.X;}
else {botPlayer = Player.O;}
String board[] = new String[3];
for(int i = 0; i < 3; i++) {
System.out.println("ENTER board: ");
board[i] = in.next();
}
currentBoard = new GameBoard(3,3, board);
List<Space> OpenSpaces = getOpenSquares(currentBoard);
MakeMove(OpenSpaces);
System.exit(-1);
}
public static List<Space> getOpenSquares(GameBoard GB) {
List<Space> OpenSpaces = new ArrayList<Space>();
for(int r = 0; r < 3; r++) {
for(int c = 0; c < 3; c++) {
if(GB.squares[r][c] == Player.Open) {
OpenSpaces.add(new Space(r,c));
}
}
}
return OpenSpaces;
}
private static Space bestMove;
private static Space currentMove;
private static Space previousMove;
private static void MakeMove(List<Space> OpenSpaces) {
if(OpenSpaces.size() == currentBoard.Size) {
Random random = new Random();
bestMove = new Space(random.nextInt(2),2);
} else {
for(Space child: OpenSpaces) {
currentMove = GetBestMove(currentBoard,botPlayer);
if (currentMove != null){
}else{
continue;}
if(previousMove != null && previousMove.Rank < currentMove.Rank ||
previousMove == null && currentMove != null) {
bestMove = currentMove;
}
previousMove = currentMove;
}
}
if (bestMove != null) {
currentBoard.squares[bestMove.X][bestMove.Y] = botPlayer;
System.out.println("the best move is: " + currentMove.X + " " + currentMove.Y);
}
}
private static Space GetBestMove(GameBoard gb, Player p) {
Space bestSpace = null;
List<Space> cloneOpenSpaces = getOpenSquares(gb);
GameBoard cloneBoard = null;
cloneBoard = gb.Clone();
for(Space Open: cloneOpenSpaces) {
cloneBoard = gb.Clone();
Space newSpace = Open;
cloneBoard.squares[newSpace.X][newSpace.Y] = p;
if(cloneBoard.Winner == Player.Open && cloneOpenSpaces.size() > 0) {
Player InP;
if(p == Player.X) {
InP = Player.O;
}else {
InP = Player.X;
}
Space tempMove = GetBestMove(cloneBoard, InP);
if(tempMove != null){
newSpace.Rank = tempMove.Rank;
}
} else {
if(cloneBoard.Winner == Player.Open) {
newSpace.Rank = 0;
}else if(cloneBoard.Winner == Player.O) {
newSpace.Rank = -1;
}else if(cloneBoard.Winner == Player.X) {
newSpace.Rank = 1;
}
}
System.out.println(newSpace.Rank);
if(bestSpace == null ||
(p == Player.X && newSpace.Rank < ((Space)bestSpace).Rank)||
(p == Player.O && newSpace.Rank > ((Space)bestSpace).Rank)) {
bestSpace = newSpace;
}
}
return (Space)bestSpace;
}
public static enum Player {
X (1),
O (-1),
Open (0);
private final double value;
Player(double value){
this.value = value;
}
}
public static class Space {
public int X;
public int Y;
public double Rank;
public Space(int x, int y) {
this.X = x;
this.Y = y;
Rank = 0;
}
public Space() {
}
}
public static class GameBoard {
public int Rows;
public int getRows() {
return this.Rows;
}
public void setRows(int rows) {
Rows = rows;
}
public int Columns;
public int getColumns() {
return this.Columns;
}
public void setColumns(int columns) {
Columns = columns;
}
public Player[][] squares;
//public Player[x][y]
public Player getPlayer(int x, int y) {
return this.squares[x][y];
}
public void setPlayer(int x, int y, Player player) {
squares[x][y] = player;
}
public boolean Full;
public boolean isFull() {
for(int r = 0; r < 2; r++) {
for(int c = 0; c < 2; c++) {
if (squares[r][c] != Player.Open) {return false;}
}
}
return true;
}
public int Size;
public int getSize() {
return this.Size;
}
public void setSize(int size) {
Size = size;
}
public List<Space> OpenSquares;
public List<Space> getOpenSquares() {
List<Space> OpenSquares = new ArrayList<Space>();
for(int r = 0; r < Rows; r++) {
for(int c = 0; c < Columns; c++) {
if(squares[r][c] == Player.Open) {
OpenSquares.add(new Space(r,c));
}
}
}
return this.OpenSquares;
}
public Player Winner;
public Player getWinner() {
int count = 0;
//columns
for (int x = 0; x < Rows; x++)
{
count = 0;
for (int y = 0; y < Columns; y++) {
count += squares[x][y].value;
}
if (count == 3) {
return Player.X;
}else if (count == -3) {
return Player.O;
}
}
//rows
for (int x = 0; x < Rows; x++) {
count = 0;
for (int y = 0; y < Columns; y++) {
count += squares[y][x].value;
}
if (count == 3) {
return Player.X;
}else if (count == -3) {
return Player.O;
}
}
// Diagonals right to left
count = 0;
count += squares[0][0].value;
count += squares[1][1].value;
count += squares[2][2].value;
if (count == 3) {
return Player.X;
}else if (count == -3) {
return Player.O;
}
// Diagonals left to right
count = 0;
count += squares[0][2].value;
count += squares[1][1].value;
count += squares[2][0].value;
if (count == 3) {
return Player.X;
}else if (count == -3) {
return Player.O;
}
return Player.Open;
}
public GameBoard Clone() {
GameBoard b = new GameBoard(Rows,Columns);
b.squares = (Player[][])this.squares.clone();
b.Winner = getWinner();
return b;
}
// Class initializer
public GameBoard(int boardRows, int boardColumns, String[] board) {
// Set the dimensions
Rows = boardRows;
Columns = boardColumns;
// Create game spaces
squares = new Player[Rows][Columns];
for(int r = 0; r < Rows; r++) {
for(int c = 0; c < Columns; c++) {
//squares[i][n] = Player.Open;
if(board[r].charAt(c) == 'X') {
squares[r][c] = Player.X;
}
if(board[r].charAt(c) == 'O') {
squares[r][c] = Player.O;
}
if(board[r].charAt(c) == '_') {
squares[r][c] = Player.Open;
}
}
}
this.Winner = getWinner();
this.OpenSquares = getOpenSquares();
//Size of the board
this.Size = Rows * Columns;
}
// clone Class initializer
public GameBoard(int boardRows, int boardColumns) {
// Set the dimensions
Rows = boardRows;
Columns = boardColumns;
// Create game spaces
squares = new Player[Rows][Columns];
for(int r = 0; r < Rows; r++) {
for(int c = 0; c < Columns; c++) {
squares[r][c] = Player.Open;
}
}
this.Winner = getWinner();
this.OpenSquares = getOpenSquares();
//Size of the board
Size = Rows * Columns;
}
}
}
all of the classes are at the bottom. Thanks in advance for any help and corrections. :)
i made it recursive in the following code, although i still cant figure out the scoring.. if the value is either 1, 0, or -1 then if there are multipule moves with the same value it will just take the 1st one which may not be the best move "blocking.
private static Space GetBestMove(GameBoard gb, Player p) {
Space bestSpace = null;
List<Space> cloneOpenSpaces = getOpenSquares(gb);
GameBoard cloneBoard = null;
cloneBoard = gb.Clone();
for(Space Open: cloneOpenSpaces) {
cloneBoard = gb.Clone();
Space newSpace = Open;
cloneBoard.squares[newSpace.X][newSpace.Y] = p;
if(cloneBoard.Winner == Player.Open && cloneOpenSpaces.size() > 0) {
Player InP;
if(p == Player.X) {
InP = Player.O;
}else {
InP = Player.X;
}
***Space tempMove = GetBestMove(cloneBoard, InP);***
if(tempMove != null){
newSpace.Rank = tempMove.Rank;
}
the results of the test are as follows
test 1
ENTER bot:
O
ENTER board:
[ ][O][ ]
ENTER board:
[ ][ ][ ]
ENTER board:
[ ][X][X]
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
-1.0
the best move is: 0 2
test 2
ENTER bot:
O
ENTER board:
[ ][X][X]
ENTER board:
[ ][ ][ ]
ENTER board:
[ ][O][ ]
1.0
1.0
1.0
1.0
1.0
-1.0
1.0
-1.0
-1.0
1.0
-1.0
1.0
1.0
-1.0
-1.0
the best move is: 1 1
I haven't ran your code, but I think I may know why you are having issues. The minimax algorithm is recursive in nature. You look at each open space, and determine some sort of score for each one. I see this in your code. However, what I don't see is the recursion that equates to the logic "if I move here, then what options will my opponent have during his next turn". Notice that you can keep calling the same scoring function, but scoring both players' options. This is where the computation can get intensive, and where stuff like pruning comes into play. Say I want to look 3 moves ahead. Say there are initially 5 open spaces. For each of the 5 open spaces, I examine my options and give a score to each one. Then I pretend to move there, and send the new board through the scoring function, and assume my opponent will take the highest scoring move of the remaining 4 possible moves. Then I pretend he moves there, and I again run the board through the scoring function, now with 2 hypothetical moves on it. You continue this for a set "depth", or number of potential moves, and pick the move that results in the highest value, assuming the opponent will do what you calculated they would.
I realize this was long-winded, but I hope there was a little bit of value buried in there somewhere. Take a look at your code, figure out where you are scoring moves (if you see a win, take it; if you can block a win, take it; etc.). Then continue calling this function where you keep adding fake/potential moves (those with the highest value from your scoring function), and once you reach the depth, you can simply pick the move that is likely to give you the most valuable outcome.
Basically, in your code, you should call GetBestMove(...) once from MakeMove(...). However, GetBestMove(...) should repeatedly call itself, with a modified board each time; and each time, it will return the best move given a hypothetical (or real) board. What I don't see in your code is that recursive call to GetBestMove(...), and the necessary upkeep that goes along with it. This explains why you only get aggressive behavior; it only looks to see what the best immediate move is, without any regard to what your opponent might be able to do if you make that move!
If my assumptions are wrong, provide a test case where you expect some behavior, but are getting something different.

Categories