Java count longest possible array - java

I'm doing a coin toss program, and am trying to determine the longest possible run of heads or tails that were tossed. I already have code for determining if toss is heads or tails, but now need to count longest possible run. Help! Here's my code for the basic program.
public static void coin_toss(char [] toss)
{
int s = 0;
try
{
for (s = 0; s <= toss.length; s++)
{
double flip;
flip = (double)(Math.random());
if (flip < 0.5)
toss[s] = 't';
else
toss[s] = 'h';
}//end of for loop to load array
}
catch (ArrayIndexOutOfBoundsException errorMessage)
{
System.out.println("\nSubscript out of bounds");
System.out.println("Subscript went past the limit of " + toss.length);
System.out.println("Last value of subscript was --> " + s);
System.out.println("-------------------------------------------------");
System.out.println(errorMessage);
System.out.println("-------------------------------------------------");
}
}//end of toss coin
public static double percent_heads (char [] toss)
{
double percent_h;
int heads = 0;
for (int s = 0; s < toss.length; s++)
{
if (toss[s] == 'h')
heads = heads + 1;
}
System.out.println("There were " + heads + " heads results");
percent_h = (double)heads / toss.length;
return (percent_h);
}//end of heads percentage function
public static double percent_tails (char [] toss)
{
double percent_t;
int tails = 0;
for (int s = 0; s < toss.length; s++)
{
if (toss[s] == 't')
tails = tails + 1;
}
System.out.println("There were " + tails + " tails results");
percent_t = (double)tails / toss.length;
return (percent_t);
}//end of tails percentage function
public static void main(String [] args)
{
int num_toss = 0;
double heads, tails;
double percent_t, percent_h;
DecimalFormat percent = new DecimalFormat ("#0.00%");
System.out.print("How many tosses would you like? --> ");
num_toss = GetInput.readLineInt();
char [] toss = new char[num_toss];
System.out.println("You chose " + toss.length + " tosses");
coin_toss(toss);
heads = percent_heads(toss);
tails = percent_tails(toss);
System.out.println("The percentage of heads was --> " + percent.format(heads));
System.out.println("The percentage of tails was --> " + percent.format(tails));
longest_toss(toss);
java.util.Date today = new java.util.Date();
System.out.println("\nProgram terminated at " + today);
System.exit(0);
}//end of main method
}//end of class

There is a method I came up with.
public static void longest_toss(char[] toss){
int longestrun = 0;
int curlongestrun = 0;
char prevrun = toss[0];
for (int s = 1; s < toss.length; s++)
{
if (toss[s] == prevrun) {
curlongestrun++;
}else {
curlongestrun=0;
}
if(curlongestrun>longestrun){
longestrun = curlongestrun;
}
prevrun = toss[s];
}
System.out.println("Longest run is : " + longestrun + " Coin side : " + prevrun);
}

You can get maximum index of the array toss[] as Integer.MAX_VALUE - 8
Here it is less by 8 because, in the source code of java.util.ArrayList class, it is clearly mentioned that, MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8 provided you have sufficient memory to hold the content of array with this much data.

int getLongestHeads(char [] toss){
int longestHeads = 0;
for(char c : toss)
{
if(longestHeads > 0 && c == 'h'){
longestHeads = longestHeads + 1;
}
else{
longestHeads = 0;
}
if(c == 'h' && longestHeads == 0) {
longestHeads = 1;
}
}
return longestHeads;
}

Related

How can I fix this variable error in my 2D Array program?

I am writing a penny pitch program in java and it is a carnival game. Prizes are randomly generated on a board and 10 coins are thrown. In the "randSelector" method I have written, I am getting an error from "prize" because it says I cant return a String to String []. Any Suggestions? This is my code:
import java.util.Arrays;
import java.util.Random;
public class PennyPitch {
public static void main(String[] args) {
// TODO Auto-generated method stub
Random rand = new Random();
String[][] board = new String[25][25];
int puzzle = 0;
int poster = 0;
int doll = 0;
int ball = 0;
int game = 0;
int misses = 0;
//Create empty board
Arrays.fill(board, "[ ]");
String[] prizes = {"[ puzzle ]", "[ poster ]", "[ doll ]", "[ ball ]", "[ game ]"};
for (int i = 0; i < prizes.length; i++) {
randSelecter(board, prizes[i], rand);
}
//Simulates 10 pennies thrown
for ( int i = 0; i < 10; i++) {
for ( int j = 0; j < 10; j++){
int box = rand.nextInt(24);
if (board[box][j] == "[ puzzle ]"){
puzzle += 1;
} else if (board[box][j] == "[ poster ]"){
poster += 1;
} else if (board[box][j] == "[ doll ]"){
doll += 1;
} else if (board[box][j] == "[ ball ]"){
ball += 1;
} else if (board[box][j] == "[ game ]"){
game += 1;
}else {
misses += 1;
}
}
System.out.println("Welcome to Penny Pitch!");
System.out.println("Land on three of a kind and win the prize!");
System.out.println("You've thrown 10 pennies on the board below,\n");
//Prints 5 x 5 board
System.out.println(board[0][0] + board[1][1] + board[2][2] + board[3][3] + board[4][4]);
System.out.println(board[5][5] + board[6][6] + board[7][7] + board[8][8] + board[9][9]);
System.out.println(board[10][10] + board[11][11] + board[12][12] + board[13][13] + board[14][14]);
System.out.println(board[15][15] + board[16][16] + board[17][17] + board[18][18] + board[19][19]);
System.out.println(board[20][20] + board[21][21] + board[22][22] + board[23][23] + board[24][24] + "\n");
System.out.println("Here is your outcome:" );
System.out.println("Puzzle: " + puzzle );
System.out.println("Poster: " + poster );
System.out.println("Doll: " + doll );
System.out.println("Ball: " + ball );
System.out.println("Game: " + game );
System.out.println("Misses: " + misses );
//Checks for a win
if ( puzzle == 3){
System.out.println("You won a puzzle!");
} else if ( poster == 3) {
System.out.println("You won a poster!");
} else if ( doll == 3) {
System.out.println("You won a doll!");
} else if ( ball == 3) {
System.out.println("You won a ball!");
} else if ( game == 3) {
System.out.println("You won a game!");
} else {
System.out.println("Sorry, you lost.");
}
}
}
//Randomly place prizes
public static String[] randSelecter(String[][] board, String prize, Random rand) {
for (int i = 0; i < 3; i++) {
int pick = rand.nextInt(24);
int anotherNum = rand.nextInt(24);
if (board[pick][anotherNum] != "[ ]" && board[pick + 1][anotherNum+1] == "[ ]" && pick != 24) {
board[pick + 1] = prize;
} else if (board[pick][anotherNum] != "[ ]" && pick != 0 && board[pick - 1][anotherNum-1] == "[ ]") {
board[pick - 1] = prize;
} else if (board[pick][pick] != "[ ]") {
for (int k = 0; k < board.length; ) {
if (board[k][anotherNum] == "[ ]") {
board[k][anotherNum] = prize;
break;
} else {
k++;
}
}
} else {
board[pick] = prize;
}
}
for(int x = 0;x<30;x++) {
for(int p = 0;p<30;p++) {
return board[x][p];
}
}
}
}
Your return type in randSelecter is String[] but you're returning a String by doing return board[x][p]. Change your return type to String:
public static String randSelecter(String[][] board, String prize, Random rand) {
...
or alternatively change what you're returning

How to output random letters in java and get the total, high score and lowest score?

Basically, I'm trying to output random uppercase letters and the loops go on forever what am I doing wrong?
I've tried other methods using java.util.Scanner for my input dialog but other than that I can't see what's wrong.
import javax.swing.*;
public class SlotMachine {
public static void main (String[] args) {
String HOWN = JOptionPane.showInputDialog ("Enter how many times you are going to play");
int HOW = Integer.parseInt (HOWN);
double counter = 0;
System.out.println("You chose to play " + HOW + " times");
for (int i = 0; i<HOW; i++) {
for (int b = 0; b<3; i++) {
double result = Math.random();
result = Math.round (result );
result = result * ((90 - 65)+1) - 65;
char resultF = (char)result;
counter = counter + result;
System.out.println ("");
System.out.println("you got: " + resultF + " which is " + result + "in ASCII code");
System.out.println("your total is: " + counter);
}
}
}
}
You have done
for (int b = 0; b<3; i++)
instead of the correct
for (int b = 0; b<3; b++)
This should help your loop terminate.

How to print out information from data used in arrays?

My code asks for a user to enter how many wins, losses, and ties 6 different sports teams have gotten throughout a season. How can I make it so that once all the information has been received, it will print out how many wins, ties, and losses each team have gotten, as well as displaying the total amount of each?
Code:
package SMKTeamStandings;
import java.util.Scanner;
public class SMKTeamStandings {
public static Scanner in = new Scanner(System.in);
public static int number(int max, int min) {
int teamchoice = 0;
for (boolean valid = false; valid == false;) {
teamchoice = in.nextInt();
if (teamchoice >= min && teamchoice <= max) {
valid = true;
} else {
System.out.println("Please enter a different value.");
}
}
return teamchoice;
}
public static boolean finished(boolean[] completedArray) {
int i = 0;
boolean done;
for (done = true; done == true;) {
if (completedArray[i++] == false) {
done = false;
}
}
return done;
}
public static void main(String[] args) {
int teamChoice = 0, gamesNum;
String[] sportteams = {"Basketball", "Football",
"Hockey", "Rugby",
"Soccer", "Volleyball"};
boolean[] completed = new boolean[sportteams.length];
int[][] Outcome = new int[64][sportteams.length];
for (boolean done = false; done == false;) {
for (int i = 0; i < sportteams.length; i++) {
System.out.print(i + 1 + " - " + sportteams[i]);
if (completed[i] == true) {
System.out.println(" - Finished");
} else {
System.out.println();
}
}
System.out.print("\nChoose a team from the list above:");
teamChoice = number(6, 1);
teamChoice--;
System.out.print("\nHow many games total did the " + sportteams[teamChoice]
+ " team play this season?: ");
gamesNum = in.nextInt();
System.out.format("\n %10s %10s %10s %10s %10s \n\n", "", "Possible Outcomes:",
"1 - Win",
"2 - Tie",
"3 - Loss");
for (int wintieloss = 0; wintieloss < gamesNum; wintieloss++) {
System.out.print("\nEnter the outcome for game "
+ (wintieloss + 1) + ": ");
Outcome[wintieloss][teamChoice] = number(3, 1);
}
System.out.println("\n");
completed[teamChoice] = true;
done = finished(completed);
If I understood you correctly, you just want to output the data you got from the user. To do that you could go through the data array using a for loop and accessing the data using indices.
for(int team = 0; team < sportteams.length; team++) { // for each team
System.out.println((team + 1) + " - " + sportteams[team]); // output the team
int game = 0; // index of the current game
while(Outcome[game][team] != 0) { // while there is data
System.out.print("Game " + (game + 1) ": " + Outcome[game][team] + " "); // print the data
game++; // increment the index
}
System.out.println("Total games: " + game); // print the last index == total number of games
System.out.println();
}

Replace a int or long with a string in for loop?

I needed to print the Fibonacci Sequence up to 50 numbers, which I eventually figured out, but I also need to replace certain numbers that are divisible by some number with certain words. I kind of figured this out. I got the words to come up, but I could not replace the number. I tried using String.valueOf and replaceAll, but the number still keeps showing up. I left that part of the code in comments because it was not working. I am going to post my code below:
public static void main(String[] args) {
long n = 50;
System.out.print("1 ");
long x = 0;
long y = 1;
String mult3 = "cheese";
String mult5 = "cake";
String mult7 = "factory";
String mult2 = "blah";
for (long i = 1; i < n; i++) {
long forSum = x + y;
x = y;
y = forSum;
if(forSum==89){
System.out.println("");
}
if(forSum==10946){
System.out.println("");
}
if(forSum==1346269){
System.out.println("");
}
if(forSum==165580141){
System.out.println("");
}
if(forSum %3 == 0){
//String mult3 = String.valueOf(forSum);
//String mult4 = "cheese";
//String mult3cheese = mult3.replaceAll(mult3, mult4);
//System.out.print(mult3cheese);
System.out.print(mult3);
}
if(forSum %5 == 0){
System.out.print(mult5);
}
if(forSum %7 == 0){
System.out.print(mult7);
}
if(forSum %2 == 0){
System.out.print(mult2);
}
System.out.print(forSum + " ");
}//for loop for forSum
}//public static void main
You need to place some "continue" statements to skip past the line that prints the number, if you have matched a "replace the number" condition:
public static void main(String[] args) {
long n = 50;
System.out.print("1 ");
long x = 0;
long y = 1;
String mult3 = "cheese";
String mult5 = "cake";
String mult7 = "factory";
String mult2 = "blah";
for (long i = 1; i < n; i++) {
long forSum = x + y;
x = y;
y = forSum;
if(forSum==89){
continue;
}
if(forSum==10946){
continue;
}
if(forSum==1346269){
continue;
}
if(forSum==165580141){
continue;
}
if(forSum %3 == 0){
//String mult3 = String.valueOf(forSum);
//String mult4 = "cheese";
//String mult3cheese = mult3.replaceAll(mult3, mult4);
//System.out.print(mult3cheese);
System.out.print(mult3 + " ");
continue
}
if(forSum %5 == 0){
System.out.print(mult5 + " ");
continue;
}
if(forSum %7 == 0){
System.out.print(mult7 + " ");
continue;
}
if(forSum %2 == 0){
System.out.print(mult2 + " ");
continue;
}
System.out.print(forSum + " ");
}//for loop for forSum
}//public static void main
"continue" means "skip the rest of the code inside this loop and do the next iteration of the loop"

Speeding up Pythogrean triple calculator

So far my code runs fine, but I need a way to speed it up. When the user enters max_values to be 25000 it takes about 1.81 seconds and I need it to be less than one second. I tried my best to optimize my triples method but I don't know what else to do.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Pythagorean {
public static void triples(int max_values){
int x = 0;
for(int c = 5; c <= max_values; c++){
int cTwo = c * c;
int b = c - 1;
for (int a = 0;a <= cTwo - b*b;a++){
if (a*a + b*b == cTwo){
x++;
System.out.println(x + ") " + a + " " + b + " " +c);
}
}
}
}
public static void main(String[] args){
System.out.println("--- Pythagorean Triple Generator ---");
System.out.println();
Scanner input = new Scanner(System.in);
int max_value = 0;
System.out.print("Enter max value for c: ");
try{
max_value = input.nextInt();
} catch (InputMismatchException ime) {
input.nextLine();
System.err.println("Error: Input is not an integer.");
System.exit(1);
}
input.close();
long start = System.currentTimeMillis();
triples(max_value);
double elapsed = (System.currentTimeMillis() - start)/ 1000.0;
System.out.println("Searching complete...");
System.out.printf("Elpased time: %.3f\n", elapsed);
}
}
This just ran in 0.999 seconds on my PC.
It uses a single StringBuilder to collect all the output, then does just one println at the end.
public static void triples(final int max_values)
{
int x = 0;
final StringBuilder sb = new StringBuilder(24000);
for (int c = 5; c <= max_values; c++)
{
final int cTwo = c * c;
final int b = c - 1;
final int bTwo = b * b;
final int cTwoLessB = cTwo - bTwo;
for (int a = 0; a <= cTwoLessB; a++)
{
if (a * a + bTwo == cTwo)
{
x++;
sb.append(x);
sb.append(") ");
sb.append(a);
sb.append(" ");
sb.append(b);
sb.append(" ");
sb.append(c);
sb.append("\n");
}
}
}
System.out.println(sb.toString());
}
The bottleneck is most likely System.out.println. Writing to the console often takes time.
for (int a = 0;a <= cTwo - b*b;a++){
if (a*a + b*b == cTwo){
x++;
System.out.println(x + ") " + a + " " + b + " " +c);//Do you really need this?
}
}
Maybe you could store it in a collection and do the printing after the loop is done (or use Stringbuilder as suggested).
Some optimizations:
int multiplyB = b*b ;//multiplication can also be slow.
for (int a = 0;a <= cTwo - multiplyB;a++){
if (a*a + multiplyB == cTwo){
++x;//use preincrement operator
str.append(x ).append(") ").append(a).append( " ").append(b).append(" ").append(c).append("\n");
}
}

Categories