I have been stuck on this for weeks, I have no idea how to do this. I just want the longest streak of heads. I have tried countless times and I just don't know what I'm doing wrong.
public class LongestStreak extends ConsoleProgram
{
public static final int FLIPS = 100;
int currentRun;
int runStart;
int maxRun;
public void run()
{
double heads = 0;
double tails = 0;
for(int i = 0; i < FLIPS; i++)
{
if(Randomizer.nextBoolean())
{
System.out.println("Heads");
heads++;
currentRun++; // use ++ in preference to +=1, and this should be before maxRun test
if (maxRun < currentRun) {
maxRun = currentRun;
runStart = currentRun - i; // this will produce a 1-based position
} else {
currentRun = 0;
}
}
else
{
System.out.println("Tails");
tails++;
}
}
System.out.println(FLIPS);
}
}
i am not sure if i understand your problem right, but here i have a solution, which will print you the longest streak within the 100 FLIPS
public static void run() {
Random r = new Random();
double heads = 0;
double tails = 0;
for (int i = 0; i < FLIPS; i++) {
if (r.nextBoolean()) {
System.out.println("Heads");
heads++;
currentRun++;
if (maxRun < currentRun) {
maxRun = currentRun;
runStart = currentRun - i;
}
} else {
System.out.println("Tails");
tails++;
currentRun = 0;
}
}
System.out.println(FLIPS);
System.out.println(maxRun);
}
public class LongestStreak extends ConsoleProgram
{
public static final int FLIPS = 100;
public void run()
{
int consecutiveHeads = 0;
int maxRun = 0;
for(int i = 0; i < FLIPS; i++)
{
if(Randomizer.nextBoolean())
{
System.out.println("Heads");
consecutiveHeads++;
if(maxRun < consecutiveHeads)
{
maxRun = consecutiveHeads;
}
}
else
{
System.out.println("Tails");
consecutiveHeads = 0;
}
}
System.out.println("Longest streak of heads: " + maxRun);
}
}
Related
App Link: Replit
I have a Neuron_ class
public class Neuron_ {
private double[] weights;
double learningRate;
public Neuron_ (int inputNeurons, double learningRate) {
this.weights = new double[inputNeurons];
this.learningRate = learningRate;
for (int i = 0; i < inputNeurons; i++) {
this.weights[i] = Math.random();
}
}
public double calculate(double[] inputs) {
double output = 0;
for(int i = 0; i < inputs.length; i++) {
output += inputs[i] * this.weights[i];
}
return output;
}
public void decreaseWeight(double[] inputs) {
for (int i = 0; i < this.weights.length; i++) {
this.weights[i] -= learningRate * inputs[i] ;
}
}
public void increaseWeight(double[] inputs) {
for (int i = 0; i < this.weights.length; i++) {
this.weights[i] += learningRate * inputs[i] ;
}
}
}
and I call increaseWeight and decreaseWeight methods from NeuralNetwork class
if(biggestIndex != correctIndex) {
System.out.println("Wrong output, changing weights");
for (int i = 0; i < this.neurons.length; i++) {
for (int j = 0; j < outputNeurons.length; j++) {
System.out.println("Changing weights for neuron " + i + " for output " + outputNeurons[j]);
if (j == correctIndex) {
this.neurons[i].increaseWeight(inputs);
} else if (j == biggestIndex) {
this.neurons[i].decreaseWeight(inputs);
}
}
}
}
neurons array is created like this
public NeuralNetwork_ (int inputNeurons, String[] outputNeurons, double learningRate) {
this.outputNeurons = outputNeurons;
this.neurons = new Neuron_[outputNeurons.length];
for(int i = 0; i<outputNeurons.length; i++) {
this.neurons[i] = new Neuron_(inputNeurons, learningRate);
}
}
When I call decreaseWeight and increaseWeight methods from another class, Logs show like they were changed but when I log weights at the beginning and at the end of the training, they were same every time.
weights array is not updating.
weights change, but finally the result is the same for maths ops.
Try modify you method with more log:
public void decreaseWeight(double[] inputs) {
double[] newWeights = new double[inputs.length];
for (int i = 0; i < this.weights.length; i++) {
newWeights[i] = this.weights[i] - learningRate;
}
this.weights = newWeights;
System.out.println("intermedial weights: " + Arrays.toString(this.weights));
}
public void increaseWeight(double[] inputs) {
double[] newWeights = new double[inputs.length];
for (int i = 0; i < this.weights.length; i++) {
newWeights[i] = this.weights[i] + learningRate;
}
this.weights = newWeights;
System.out.println("intermedial weights: " + Arrays.toString(this.weights));
}
and study the result.
For each neurons iterator you are increasing and then decreasing weights whith the same value, so finally neuron weights are the same
I have a class Game which add to the logs score of my game.
Then I want to add the limit, that I can only 2 logs add for example and than logs don't added. But what I should to add in my Game.class that the class will communicate with the file log.properties? Should I use log4j?
Here is my Game.class:
import java.util.Random;
import java.util.logging.Logger;
public class Game {
public static final int numOfFutMarbles = 3; // przyszle kulki
private int score;
Field fieldProcessor = new Field();
Wave wave = new Wave();
Logger logger = Logger.getLogger(Game.class.getName());
Random random = new Random();
public final static int width = 9; // rozmiar planszy
public final static int height = 9;
public Bin[][] field;
public static final int not_sel = -1;
int activeBinX = not_sel;
int activeBinY = not_sel;
public Game() {
this.field = new Bin[width][height];
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
field[i][j] = new Bin(i, j);
}
}
placeMarbles(5, Marble.new_mar); // liczba kulek na poczatku
placeMarbles(3, Marble.fut_mar); // liczba przyszlych kulek
score = 0;
}
public void BinSelected(int i, int j) {
if (isBinContainsMarble(i, j)) {
activeBinchange(i, j);
}
}
boolean isBinContainsMarble(int i, int j) {
return field[i][j].isBinContainsMarble();
}
public void makeMoveOrSelect(int i, int j) {
if (field[i][j].isBinContainsMarble()) {
activeBinchange(i, j);
return;
}
if (activeBinX == not_sel) {
return;
}
if (wave.isMoveAvailable(field, activeBinX, activeBinY, i, j)) {
makeMove(i, j);
}
}
void makeMove(int x, int y) {
field[x][y].marble = field[activeBinX][activeBinY].marble;
field[x][y].setMarbleState(Marble.inac_mar);
field[activeBinX][activeBinY].marble = null;
activeBinX = not_sel;
activeBinY = not_sel;
boolean isLineRemoved = fieldProcessor.checkField(field);
if (!isLineRemoved) {
placeNewMarbles();
fieldProcessor.checkField(field);
}
calcScores();
wave.createWaveArrayFrom(field);
}
void activeBinchange(int i, int j) {
if (isActiveBinSelected()) {
field[activeBinX][activeBinY].setMarbleState(Marble.inac_mar);
}
field[i][j].setMarbleState(Marble.act_mar);
activeBinX = i;
activeBinY = j;
}
private boolean isActiveBinSelected() {
return activeBinX > not_sel;
}
void placeNewMarbles() {
int remaningFutureMarbles = calcRemaningFutureMarblesAndMakeThemNEW();
placeMarbles(numOfFutMarbles, Marble.fut_mar);
}
int calcRemaningFutureMarblesAndMakeThemNEW() {
int remainingFutureMarblesAmount = 0;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (field[i][j].getMarbleState() == Marble.fut_mar) {
remainingFutureMarblesAmount++;
field[i][j].setMarbleState(Marble.new_mar);
}
}
}
return remainingFutureMarblesAmount;
}
void placeMarbles(int n, int state) {
for (int i = 0; i < n; i++) {
placeMarbleOnEmptySpace(state);
}
}
void placeMarbleOnEmptySpace(int state) { // umieszamy kulke na wolnym miejscu
boolean isPlaced = false;
do {
int i = random.nextInt(width);
int j = random.nextInt(height);
if (field[i][j].getMarbleState() == 0) {
field[i][j].marble = new Marble(state);
isPlaced = true;
}
} while (!isPlaced);
}
public void updateBins() {
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (field[i][j].marble != null) {
field[i][j].marble.porcessMarbles();
}
}
}
}
public int calcScores() {
int markedForDel = 0;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (field[i][j].marble != null) {
if (field[i][j].marble.MarbleState == Marble.mark_for_rem) {
markedForDel++;
}
}
}
}
if (markedForDel > 0) {
int bon = (int) (4 + Math.pow(markedForDel - 4, 3)); // 6 kulek = 12 pkt, 7 kulek - 31 pkt
score += bon;
logger.info(score + "");
System.out.println("your score: " + score); // 1 pkt za kazda kulke
}
return score;
}
}
Here is my log configuration:
handlers = java.util.logging.FileHandler, java.util.logging.ConsoleHandler
.level = ALL
# File Logging
java.util.logging.FileHandler.pattern=./logs/Marbles_game.log
java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter
java.util.logging.FileHandler.level=ALL
java.util.logging.FileHandler.limit=2
java.util.logging.FileHandler.count=100
# Console Logging
java.util.logging.ConsoleHandler.level = OFF
Add java.util.logging.FileHandler.append=true to your properties file. This will append data to the log file until it reaches the limit.
I am interested in implementing the Rabin-Karp algorithm to search for sub strings. Here is the algorithm i used: algorithm.
The code I made for the same is as below.
But output is blank. It says build successfully but gives no output...
package rabinkarp;
public class RabinKarp {
final static int q = 101;
final static int d = 256;
public static void RabinKarpMatcher(String T,String p,int q,int d)
{
int n = T.length();
int M = p.length();
int H = 1,i,j;
for (i = 0; i < M-1; i++)
H = (H*d)%q;
int P = 0;
int t = 0;
for(i = 0;i < M; i++)
{
P = (d*P+p.charAt(i))%q;
t = (d*t+T.charAt(i))%q;
}
for(i = 0; i < n-M; i++)
{
if(P==t)
{
for(j = 0; j < M; j++)
{
if(T.charAt(i+j)!=p.charAt(j))
{
break;
}
}
if(j==M)
{
System.out.println("Pattern found at " + i+1);
}
}
if(i < n-M)
{
t = (d*(t-T.charAt(i)*H)+T.charAt(i+M))%q;
if(i <0)
{
t = t+q;
}
}
}
}
public static void main(String[] args) {
String text = new String("ababaaabhahhhha");
String pat = new String("ha");
RabinKarpMatcher(text,pat,q,d);
}
}
I want ask a little question about my program.
This is my code sample:
public static void main(String[] args) {
int q;
int p;
int thelargest;
int thesmallest;
Scanner input = new Scanner(System.in);
System.out.println("Enter the list of number : ");
String input2 = input.nextLine();
String[] numbers = input2.split(" ");
int[] result = new int[numbers.length];
for (p = 0; p < numbers.length; p++) {
result[p] = Integer.parseInt(numbers[p]);
}
for (q = 0; q < result.length; q++) {
System.out.print("");
System.out.println(result[q]);
}
System.out.println("Largest Number : " + LargestNumber(result));
System.out.println(" Smallest Number : " + SmallestNumber(result));
thelargest = LargestNumber(result);
thesmallest = SmallestNumber(result);
System.out.println("The Arithmetic Mean : "
+ AirthmeticMean(result, thesmallest, thelargest));
}
public static int SmallestNumber(int[] series) {
int thesmallest = series[0];
for (int i = 1; i < series.length; i++) {
if (series[i] < thesmallest) {
thesmallest = series[i];
}
}
return thesmallest;
}
public static int LargestNumber(int[] series) {
int thelargest = series[0];
for (int i = 1; i < series.length; i++) {
if (series[i] > thelargest) {
thelargest = series[i];
}
}
return thelargest;
}
public static float AirthmeticMean(int[] result, int thesmallest,
int thelargest) {
int sum = 0;
for (int i = 0; i < result.length; i++) {
sum += result[i];
}
sum -= thesmallest;
sum -= thelargest;
return (float) sum / result.length;
}
How can I convert this code sample to the ConsoleProgram (which is in the ACM library)?
Which parts must I change or add?
I started with:
public class ArithmeticMean extends ConsoleProgram {
}
But I do not know what to do next.
In acm library no main method though you need to use instead the following construction:
public void run() {}
Here is an API of this library http://jtf.acm.org/javadoc/student/
Select acm.program package ConsoleProgram class and find appropriate methods
see also acm.io / class IOConsole
e.g. System.out.println() --> println()
Scanner (String input) --> readLine(String prompt) etc.
the rest is the same as you in your code.
Ok, here you are your code in acm: (a bit ugly but works fine:)
import acm.program.ConsoleProgram;
public class StackOverflow extends ConsoleProgram
{
private static final long serialVersionUID = 1L;
public void run()
{
int q;
int p;
int thelargest;
int thesmallest;
String input2 = "";
String[] numbers = null;
println("Enter the list of number : ");
while (true) {
String input = readLine();
if (input.equals(""))
break;
input2 += input + " ";
}
numbers = input2.split(" ");
int[] result = new int[numbers.length];
for (p = 0; p < numbers.length; p++) {
result[p] = Integer.parseInt(numbers[p]);
}
for (q = 0; q < result.length; q++) {
print("");
println(result[q]);
}
println("Largest Number : " + LargestNumber(result));
println(" Smallest Number : " + SmallestNumber(result));
thelargest = LargestNumber(result);
thesmallest = SmallestNumber(result);
println("The Arithmetic Mean : "
+ AirthmeticMean(result, thesmallest, thelargest));
}
public static int SmallestNumber(int[] series)
{
int thesmallest = series[0];
for (int i = 1; i < series.length; i++) {
if (series[i] < thesmallest) {
thesmallest = series[i];
}
}
return thesmallest;
}
public static int LargestNumber(int[] series)
{
int thelargest = series[0];
for (int i = 1; i < series.length; i++) {
if (series[i] > thelargest) {
thelargest = series[i];
}
}
return thelargest;
}
public static float AirthmeticMean(int[] result, int thesmallest,
int thelargest)
{
int sum = 0;
for (int i = 0; i < result.length; i++) {
sum += result[i];
}
sum -= thesmallest;
sum -= thelargest;
return (float) sum / result.length;
}
}
And Run as JavaApplet
Ok, the title might be deceiving. All i want to do is take my Bingo program and when the second bingo card is printed, i want to replace all the "0"'s with "X"'s. I was thinking i would have to go and change the array to an string, but i'm not surer where to start.
Here is the Bingo program:
import java.util.*;
import java.io.*;
import java.util.Arrays;
public class Bingo
{
public static final int ROWS = 5;
public static final int COLS = 5;
public static final int VERTICAL = 1;
public static final int DIAGONAL = 2;
public static final int HORIZONTAL = 3;
public static int winFound;
public static int currPick = 0;
public static int randomPick = 0;
public static int WinFound;
public static void main(String[] args)
{
int Totcards;
int[][] card = new int[ROWS][COLS];
int[] picks = new int[25];
fillCard (card);
printCard(card);
playGame(card);
printCard(card);
finalCard(card);
}
private static void fillCard (int[][] card)
{
// FileReader fileIn = new FileReader("Bingo.in");
// Bufferreader in = new Bufferreader(fileIn);
try {
Scanner scan = new Scanner(new File("bingo.in"));
for (int i=0; i<card.length; i++){
for (int j=0; j<card[0].length; j++){
card[i][j] = scan.nextInt();
}
}
} catch(FileNotFoundException fnfe) {
System.out.println(fnfe.getMessage());
}
}
private static void printCard (int[][] card)
{
System.out.println("\n\tYOUR BINGO CARD : ");
System.out.println("\n\tB I N G O");
System.out.println("\t----------------------");
for (int i=0; i<card.length; i++){
for (int j=0; j<card[0].length; j++){
System.out.print("\t" + card[i][j]);
}
System.out.print("\n");
}
}
private static void playGame (int[][] card)
{
int numPicks = 0;
System.out.println("\n\tBINGO NUMBERS PICKED AT RANDOM FROM BIN: ");
while (true)
{
markCard (card); // Generate a random num & zero-it out
winFound = checkForWin(card); // Look for zero sums
numPicks++;
if (winFound != 0)
{
if (winFound == 1)
{
System.out.print("\n\n\tYOU WIN WITH A VERTICAL WIN AFTER " + numPicks + " PICKS\n");
}
else if (winFound == 2){
System.out.print("\n\n\tYOU WIN WITH A DIAGONAL WIN AFTER " + numPicks + " PICKS\n");
}
else if (winFound == 3){
System.out.print("\n\n\tYOU WIN WITH A HORIZONTAL WIN AFTER " + numPicks + " PICKS\n");
}
announceWin (numPicks);
return;
}
}
}
private static void markCard (int[][] card)
{
int randomPick = (int) (Math.random() * 74) + 1;
for (int j = 0; j < ROWS; j++){
for (int k = 0; k < COLS; k++){
if (card[j][k]==randomPick)
card[j][k] = 0;}
}
System.out.print("\t " + randomPick + " ");
System.out.print("");
}
private static int checkForWin(int[][] card)
{
int sum=0;
for (int i = 0; i < ROWS; i++)
{
sum = 0;
for (int j = 0; j < COLS; j++)
sum += card[i][j];
if (sum == 0)
return HORIZONTAL;
}
for (int j = 0; j < COLS; j++)
{
sum = 0;
for (int i = 0; i < ROWS; i++)
sum += card[i][j];
if (sum == 0)
return VERTICAL;
}
sum = 0;
for (int i = 0; i < ROWS; i++)
sum += card[i][ROWS-i-1];
if (sum == 0)
return DIAGONAL;
sum = 0;
for (int i = 0; i < ROWS; i++)
sum += card[i][i];
if (sum == 0)
return DIAGONAL;
return WinFound;
}
private static void makeCard(int[][] card, int[] picks)
{
int count = 100;
int currPick = 0;
for (int i=0; i<count; i++){
currPick = (int)(Math.random() * 74) + 1;
System.out.print(" " + currPick + "\n");
picks[i] = currPick;
}
}
private static void announceWin(int numPicks)
{
}
private static boolean duplicate (int currPick, int[] picks, int numPicks)
{
for (int i = 0; i < numPicks; i++){
if (picks[i] == currPick){
return true;}
}
return false;
}
private static void finalCard (int[][] card)
{
Arrays.sort(card);
final String stringRep = Arrays.toString(card);
final String[] out =
stringRep.substring(1, stringRep.length() - 1).split("\\s*,\\s*");
System.out.println(Arrays.toString(out));
}
}
Try this:
System.out.print("\t" + (card[i][j] == 0 ? "X" : card[i][j]))
Why don't you just use a String[][] for the fields from the beginning? You can still compare String values with ints (with Integer.valueOf for instance) and this way you don't have to switch types runtime...