I have a program in which it rolls five dice and assigns a hand to the rolls. i.e. nothing, a pair, two pair, three of a kind, full house, four of a kind, five of a kind. The code runs 1000000 times and gives percentage chances for each roll. Below I have attached general percentages my code should output near:
Case 1, None alike, is 0.092533
Case 2, One pair, is 0.462799
Case 3, Two pair, is 0.231789
Case 4, Three of a kind, is 0.154192
Case 5, Full house, is 0.038595
Case 6, Four of a kind, is 0.019316
Case 7, Five of a kind, is 0.000776
However my code gives the following output:
Case 1, None alike is 0.093099
Case 2, One pair is 0.384768
Case 3, Two pair is 0.076921
Case 4, Three of a kind is 0.15485
Case 5, Full House is 0.270349
Case 6, Four of a kind is 0.019281
Case 7, Five of a kind is7.33E-4
I don't understand why my programs percentages are off for one pair, two pairs, and full house. I have gone through and tested my logic but it is sound from what I have seen. Originally, my one pair was correct but my two pair was 0.0. Below is my original logic which causes the two pair to be 0 and my pair to be correct.
I, however, changed it to the current logic to get the current output. I would appreciate another set of eyes to take a look and let me know if they could catch something. Below is my code:
Change 1 :
if (hand < 6) {
int counter3 = 0;
int counter2 = 0;
for (int j = 0; j < length; j++) {
if (counts[j] == 3) {
counter3++;
}
if (counts [j] == 2) {
counter2++;
}
}
if (counter3 == 1 && counter2 == 1) {
hand = 5;
}
}
Change 2:
if (hand < 4) {
int newcounter = 0;
for (int j = 0; j < length; j++) {
if (counts[j] == 2) {
newcounter++;
}
}
if (newcounter==2) {
hand = 3;
}
if (newcounter == 1) { hand = 2; }
}
Change 3 :
Please remove if( hand < 3) part of code.
Updated my answer. In your code the counter variable (when you're trying to check "full house") was becoming 2 due to two pairs (ex : counts = 020200) not due to full house (ex: counts = 300200). Hence, it wasn't counting the two pairs in the following code where it was supposed to because hand was already becoming 5, so it didn't go inside any other if parts below although it was supposed to go inside if(hand<3). Hope it will fix the issue.
See comment in code
if (hand < 4) {
int newcounter = 0;
boolean firstp = false;
boolean secondp = false;
for (int j = 0; j < length; j++) {
firstp = false;
secondp = false;
if (counts[j] == 2) {
firstp = true; <---- THIS
}
if (counts[j] == 2) {
secondp = true; <---- AND THIS will always hit together as j never changes from the first if to second if
// break;
}
}
if (firstp && secondp) {
hand = 3; <---- firstp always equal to secondp, I would be surprised to see hand ever = 2
}
}
I modified your code. The original logic is a little bit messy. I made some slight improvement but hopefully better. Not perfect though.
import java.util.*;
public class PokerDice {
public static void main(String[] args) {
double none = 0;
double pair = 0;
double twop = 0;
double threep = 0;
double full = 0;
double fourp = 0;
double fivep = 0;
for (int i = 0; i<=1000000; i++) {
int [] rolls = new int[5];
for (int j = 0; j < 5; j++) {
rolls[j] = (int)(1 + (Math.random()*(6)));
}
int[] counts = Counts(rolls);
boolean has_two = false;
boolean has_three = false;
none++;
for (int j = 0; j < counts.length; j++) {
if (counts[j] == 4) {
fourp++;
none--;
break;
}
if (counts[j] == 5) {
fivep++;
none--;
break;
}
if (counts[j] == 3) {
has_three = true;
if (has_two) {
full++;
pair--;
break;
} else {
none--;
threep++;
}
}
if (counts[j] == 2) {
if (has_two) {
twop++;
pair--;
break;
}
else if (has_three) {
full++;
threep--;
break;
} else {
has_two = true;
pair++;
none--;
}
}
}
}
fivep/=1000000;
fourp/=1000000;
full/=1000000;
threep/=1000000;
twop/=1000000;
pair/=1000000;
none/=1000000;
System.out.println("Poker Dice Probability Calculator");
System.out.println("Running 1,000,000 trials");
System.out.println();
System.out.println("Case 1, None alike is "+none);
System.out.println("Case 2, One pair is "+pair);
System.out.println("Case 3, Two pair is "+twop);
System.out.println("Case 4, Three of a kind is "+threep);
System.out.println("Case 5, Full House is "+full);
System.out.println("Case 6, Four of a kind is "+fourp);
System.out.println("Case 7, Five of a kind is"+fivep);
}
public static int[] Counts (int [] rolled) {
int one = 0;
int two = 0;
int three = 0;
int four = 0;
int five = 0;
int six = 0;
int len = rolled.length;
int [] rolltimes = new int[6];
for (int i = 0; i<len; i++) {
if (rolled [i] == 1) {
one++;
}
else if (rolled [i] == 2) {
two++;
}
else if (rolled [i] == 3) {
three++;
}
else if (rolled [i] == 4) {
four++;
}
else if (rolled [i] == 5) {
five++;
}
else if (rolled [i] == 6) {
six++;
}
}
rolltimes[0] = one;
rolltimes[1] = two;
rolltimes[2] = three;
rolltimes[3] = four;
rolltimes[4] = five;
rolltimes[5] = six;
return rolltimes;
}
}
Related
In the code below i try to read a file with the size of a 2d array and the numbers for each cell. Then the program must find a number that can be added in the cell with a zero value in magic array. All this in order to create magic squares based on the initialized magic array with the elements of the external file. The problem is that i always get the message "magic squares cannot be created" even when the if statement in next_successor method get true from all the arguments? where is the problem? i got really stuck any help will be appreciated!
so i think the main problem is with the methods:
next_successor
check_row
check_column
check_diagonals
The rules that i have to follow in order to create the methods are:
In order for current_number to be inserted into magic[row,column], the following checks (by check_row(), check_column() and check_diagonals()) should be made:
For each of the row, column, and possibly main diagonals (in the case of row=column or row=N-column-1) to which position magic[row,column] belongs, and for each current_number that does not has yet been inserted into the magic square (according to the value used[current_number-1]), we perform the following checks to decide whether current_number can be inserted into magic[row,column]:
Suppose (in the row or column or main diagonal where the position magic[row,column]) is located after the number current_number is placed in the position magic[row,column], m positions have been filled, so there are N-m empty positions left to be filled.
Let π be the sum of the numbers already in the row or column or main diagonal (including current_number).
Let π be the sum of the πβπ smallest numbers (from 1 to N*N) not yet entered into the magic square (according to the table used) and π the sum of the πβπ largest numbers not yet entered (similarly) . If π=π then π=π=0.
Let πΆ be the magic constant. If π +π>πΆ or π +π<πΆ, for some row or column or main diagonal to which magic[row, column] belongs, then current_number cannot be inserted into position magic[row,column ], i.e. the respective check_row(), check_column() and check_diagonals() will return false, otherwise they will all return true.
the txt external file has the following elements:
6
0 0 13 0 20 0
0 15 0 0 0 12
8 0 2 0 31 0
0 14 0 7 0 1
28 0 0 0 0 0
0 0 6 0 0 21
import java.io.*;
import java.util.*;
public class MainSolver{
static ArrayList<MagicSquare> stuckAL;
static Stack<MagicSquare> stuckST;
static LinkedList<MagicSquare> stuckLL;
static int datastructure;
static int N = 0;
static int[][] input;
public static void main() throws IOException {
//THE PROGRAM READS THE EXTERNAL FILE
Scanner sc = new Scanner(System.in);
System.out.print("Enter the file name: ");
String fileName = sc.next();
System.out.println("Enter data structure to use: (arraylist, stack, queue, linkedlist): ");
System.out.println("1: arraylist");
System.out.println("2: stack");
System.out.println("3: queue");
System.out.println("4: linkedlist");
datastructure = sc.nextInt();
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
N = fileScanner.nextInt();
input = new int[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
input[i][j] = fileScanner.nextInt();
}
}
MagicSquare.size = N;
MagicSquare ms = new MagicSquare();
for(int i=0; i<N ;i++){
for(int j=0; j<N ;j++){
ms.set_cell(i,j,input[i][j]);
if (ms.magic[i][j] != 0) {
ms.used[ms.magic[i][j]-1] = true;
}
}
}
ms.check_used();
//PRINTING THE INPUT AND MAGIC ARRAY
System.out.println("Size of array from file: "+N);
ms.display(input);
System.out.println();
System.out.println("Size of array from MagicSquare object: "+ms.N);
ms.display(ms.magic);
fileScanner.close();
//IT STARTS THE INITIALIZATION OF DATASTRUCTURES & START THE SEARCH OF SUCCESSORS
initialize_search(ms,datastructure);
search(datastructure);
}
//THIS PART OF CODE NEEDS TO STAY AS IT IS. CAN'T MAKE CHANGES
static void initialize_search(MagicSquare ms, int datastructure) {
switch (datastructure) {
case 1:
case 2:
stuckAL = new ArrayList();
stuckAL.add(ms);
break;
case 3:
stuckST=new Stack();
stuckST.push(ms);
break;
case 4:
stuckLL=new LinkedList();
stuckLL.add(ms);
break;
default:
break;
}
}
//THIS PART OF CODE NEEDS TO STAY AS IT IS. CAN'T MAKE CHANGES
static void search(int datastructure) {
MagicSquare current = null, next;
switch (datastructure) {
case 1:
System.out.println("Search using ArrayList as a Stack");
break;
case 2:
System.out.println("Search using ArrayList as a Queue");
break;
case 3:
System.out.println("Search using Stack as a Stack");
break;
case 4:
System.out.println("Search using LinkedList as a Queue");
break;
default:
break;
}
boolean empty_frontier=false;
while (!empty_frontier) {
if (datastructure == 1) {
current = stuckAL.get(stuckAL.size()-1);
stuckAL.remove(stuckAL.size()-1);
}
else if (datastructure == 2) {
current = stuckAL.get(0);
stuckAL.remove(0);
}
else if (datastructure == 3)
current = stuckST.pop();
else if (datastructure == 4)
current = stuckLL.removeFirst();
current.initialize_successors();
while((next=current.next_successor()) != null)
{
if (next.numbers == N*N)
{
System.out.println("SOLUTION FOUND ");
System.out.println("==============");
next.display(next.magic);
return;
}
else switch (datastructure) {
case 1: ;
case 2: stuckAL.add(next);
break;
case 3: stuckST.push(next);
break;
case 4: stuckLL.addLast(next);
break;
}
}
switch (datastructure) {
case 1:
if (stuckAL.isEmpty())
empty_frontier=true;
break;
case 2:
if (stuckAL.isEmpty())
empty_frontier=true;
break;
case 3:
if (stuckST.isEmpty())
empty_frontier=true;
break;
case 4:
if (stuckLL.isEmpty())
empty_frontier=true;
break;
}
}
System.out.println("MAGIC SQUARES CANNOT BE CREATED");
}
}
class MagicSquare {
public static int size;
public int N;
public int C;
public int[][] magic;
public boolean[] used;
public int numbers;
public int row;
public int column;
public int current_number;
//THIS CONSTRUCTOR WITHOUT ARGUMENTS INITIALIZE N and C, the magic array and the numbers variable with zeros, as well as the used array with false values.
public MagicSquare() {
this.N = size;
C = N*((N*N+1)/2);
magic = new int[N][N];
used = new boolean[N*N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
magic[i][j] = 0;
}
}
for (int i = 0; i < used.length; i++) {
used[i] = false;
}
numbers = 0;
row = 0;
column = 0;
current_number = 0;
}
//THIS CONSTRUCTOR creates a copy of the object (mainly regarding the N, C, magic, numbers and used variables)
public MagicSquare(MagicSquare ms) {
N = ms.N;
C = ms.C;
magic = new int[N][N];
used = new boolean[N*N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
magic[i][j] = ms.magic[i][j];
}
}
for (int i = 0; i < used.length; i++) {
used[i] = ms.used[i];
}
numbers = ms.numbers;
row = ms.row;
column = ms.column;
current_number = ms.current_number;
}
//METHOD THAT IS CALLED TO FILL EACH CELL OF MAGIC ARRAY WITH NUMBER FROM EXTERNAL FILE
public void set_cell(int row, int col, int number){
if (number>=1 && number<=N*N && row>=0 && row<N*N && col>=0 && col<N*N && magic[row][col]==0){
magic[row][col] = number;
numbers++;
}
}
//METHOD THAT: "initializes" the process of constructing the "successors" of a MagicSquare object. As a successor we characterize a new object, which is in principle the same as its "parent" (with regard to the fields magic, numbers and used), but has an additional position of the magic square filled in in a valid way. The initialize_successors() method will practically give as values to the row and column fields the row and column of the next null of the magic table, while in addition it will initialize the value of the current_number field (eg, to 0).
public void initialize_successors() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (magic[i][j] == 0) {
row = i;
column = j;
current_number = 0;
return;
}
}
}
}
//METHOD THAT: each time it is called it will find the next value of current_number that can be placed in magic[row,column], construct an object that is a copy of the current object, but with the current_number in magic[row,column], and will return it. If no next value of current_number is found that can be inserted into magic[row, column], it will return null. In order for the current value of current_number to be inserted in the magic[row, column] position, this value must not already be used in the magic square (checked via the used table), and the methods check_row(), check_column() and check_diagonals() to return true.
public MagicSquare next_successor() {
MagicSquare successor;
while (current_number < N*N) {
current_number++;
if (!used[current_number-1] && check_row() && check_column() && check_diagonals()) {
successor = new MagicSquare(this);
successor.magic[row][column] = current_number;
successor.used[current_number-1] = true;
successor.numbers++;
/*if(column == N-1) {
successor.row++;
successor.column = 0;
}
else {
successor.column++;
}*/
System.out.println("next successor returns successor!");
return successor;
}
//break;
}
System.out.println("next successor returns null!");
return null;
}
//METHOD THAT: returns true if current_number is consistent with the row numbers of magic[row,column], otherwise returns false.
public boolean check_row(){
int sum = current_number;
int m = numbers;
int emptyPositions = N - m;
int a = getSumOfSmallestElementsNotUsed();
int b = getSumOfLargestElementsNotUsed();
System.out.println();
System.out.println("current number being tested in row: "+current_number);
for (int i = 0; i < N; i++) {
if (magic[row][i] != 0) {
sum += magic[row][i];
}
}
System.out.println("sum of numbers in row: "+sum);
if (sum + a > C || sum + b < C) {
System.out.println("row gives false!");
return false;
}
System.out.println("row gives true!");
return true;
}
//METHOD THAT: returns true if current_number is consistent with the column numbers of magic[row,column], otherwise returns false.
public boolean check_column(){
int sum = current_number;
int m = numbers;
int emptyPositions = N - m;
int a = getSumOfSmallestElementsNotUsed();
int b = getSumOfLargestElementsNotUsed();
System.out.println("current number being tested in column: "+current_number);
for (int i = 0; i < N; i++) {
if (magic[i][column] != 0) {
sum += magic[i][column];
}
}
System.out.println("sum of numbers in column: "+sum);
if (sum + a > C || sum + b < C) {
System.out.println("column gives false!");
return false;
}
System.out.println("column gives true!");
return true;
}
//METHOD THAT: which will return true if current_number is consistent with the numbers of each of the two main diagonals of the magic square, provided that magic[row,column] belongs to one or the other or both of the main diagonals of the magic square respectively, otherwise it will return false.
public boolean check_diagonals(){
int sum = current_number;
int m = numbers;
int emptyPositions = N - m;
int a = getSumOfSmallestElementsNotUsed();
int b = getSumOfLargestElementsNotUsed();
System.out.println("current number being tested in diagonals: "+current_number);
if (row == column) { //main diagonal
for (int i = 0; i < N; i++) {
if (magic[i][i] != 0) {
sum += magic[i][i];
}
}
} else if (row == N-column-1) { //other diagonal
for (int i = 0; i < N; i++) {
if (magic[i][N-i-1] != 0) {
sum += magic[i][N-i-1];
}
}
}
System.out.println("sum of numbers in diagonal: "+sum);
if (sum + a > C || sum + b < C) {
System.out.println("diagonals gives false!");
return false;
}
System.out.println("diagonals gives true!");
return true;
}
//METHOD THAT: calculate the sum of the 2 first empty elements of used array and therefore the smallest
public int getSumOfSmallestElementsNotUsed(){
int sum = 0;
int count = 0;
for (int i = 0; i < used.length; i++) {
if (!used[i]) {
sum += (i + 1);
count++;
}
if (count == 2) {
break;
}
}
System.out.println("sum of 2 smallest elements: "+sum);
return sum;
}
//METHOD THAT: calculate the sum of the 2 last empty elements of used array and therefore the largest
public int getSumOfLargestElementsNotUsed(){
int sum = 0;
int count = 0;
for (int i = used.length - 1; i >= 0; i--) {
if (!used[i]) {
sum += (i + 1);
count++;
}
if (count == 2) {
break;
}
}
System.out.println("sum of 2 largest elements: "+sum);
return sum;
}
public boolean isComplete() {
return numbers == N*N;
}
public void display(int array[][]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
System.out.println();
}
public void check_used(){
int i,j;
int k=0;
for(i=0; i<magic.length; i++){
for(j=0; j<magic[i].length; j++){
System.out.println("POSITION IN USED ARRAY: "+k+" WITH VALUE: "+used[k]+" FROM POSITION IN MAGIC ARRAY: "+i+","+j+" WITH VALUE: "+magic[i][j]);
k++;
}
}
}
}
What do you think this computes?
this.N = size;
C = N*((N*N+1)/2); // C = 108
The size is 6 for your problem.
So you will need the values 1 thru 36 inclusive.
let max = N*N. So the sum of 1 thru 36 is max*(max+1)/2.
divide by N to get the col or row sum and you ((max*(max+1))/2)/N = 111.
or (N*(max+1))/2)
in your case is should have been (N*(N*N+1))/2.
The issue was that. (N*N+1) is 37. Then you divide by 2 which drops the fraction (int arithemetic). You need to first multiply by N and then divide by 2.
I have some code that shuffles a deck of cards by assigning randomly chosen cards from a 2D array cards into an ArrayList deck, but when I run the code it gets stuck in an infinite loop.
It was working fine at first but seemed to randomly stop working with little change to the code.
cards is a 13 x 4 array with a different card in each position.
ArrayList<String> deck = new ArrayList<String>();
for (int i = 0; i < 52; i++) {
int v = 0;
int s = 0;
Boolean notInDeck = false;
while (!notInDeck) {
v = rand.nextInt(13);
s = rand.nextInt(4);
if (!deck.contains(cards[v][s])) {
notInDeck = true;
deck.add(cards[v][s]);
}
}
}
I tried adding outputs at different points to try and track what was happening
ArrayList<String> deck = new ArrayList<String>();
for (int i = 0; i < 52; i++) {
System.out.println("1");
int v = 0;
int s = 0;
Boolean notInDeck = false;
while (!notInDeck) {
System.out.println("2");
v = rand.nextInt(13);
s = rand.nextInt(4);
if (!deck.contains(cards[v][s])) {
System.out.println("3");
notInDeck = true;
deck.add(cards[v][s]);
}
System.out.println("4");
}
System.out.println("5");
}
System.out.println("6");
There are no error messages.
The output is fine for the first bunch of run-throughs, being 1 2 3 4 5 1 2 3 4 5, but ends up infinitely repeating 2 4 2 4 2 4...
It should be like 1 2 3 4 5 1 2 3 4 5 then maybe sometimes 1 2 4 2 3 4 5 when it repeats a set of random numbers.
Here is my code for the cards 2D array.
String[][] cards = new String[13][4];
String suit = " ";
String value = "";
for (int i = 0; i < 13; i++) {
for (int j = 0; j < 4; j++) {
if (j == 0) {
suit = "C";
} else if (j == 1) {
suit = "H";
} else if (j == 2) {
suit = "S";
} else if (j == 3) {
suit = "D";
}
if (i == 0) {
value = "A";
} else if (i == 10) {
value = "J";
} else if (i == 11) {
value = "Q";
} else if (i == 12) {
value = "K";
} else {
value = Integer.toString(i+1);
}
cards[i][j] = value;
}
}
Edit:
I realised the issue was with this line
cards[i][j] = value;
It should be
cards[i][j] = value + " " + suit;
You are making your life harder.
In real life, you are not taking gazillion of cards and you are not randomly picking cards until you complete full 52 cards deck. In fact, you start with 52 cards and you suffle them. Do the same here
Create collection of 52 cards
Shuffle that collection (eg. with Collections.shuffle)
While this is simply linear operation, your solution is indeterministic.
It shouldn't run indefinitely unless you are having an unlucky day or have initialized cards array with wrong values.
So, this is what happening. Since you are using a random guess to put a card into the deck, with each attempt it's harder and harder for random generator to find, so to say, a card that was not placed in the deck yet. At the of the day you will have more and more attempts to place last cards correctly. The number of those attempts could reach hundreds and even thousands.
I have added a couple of lines to your code and visualized the problem on Ideone.
ArrayList<String> deck = new ArrayList<String>();
HashMap<Integer, Integer> guesses = new HashMap<>();
for (int i = 0; i < 52; i++) {
int guess = 0;
int v = 0;
int s = 0;
Boolean notInDeck = false;
while (!notInDeck) {
v = rand.nextInt(13);
s = rand.nextInt(4);
guess++;
if (!deck.contains(cards[v][s])) {
notInDeck = true;
deck.add(cards[v][s]);
guesses.put(i, guess++);
}
}
}
for (Map.Entry<Integer, Integer> entry: guesses.entrySet()) {
System.out.printf("%2s : %s\n", entry.getKey(), entry.getValue());
}
If you execute the code several times, you will clearly see the patternβthe number of guesses grows significantly at the end.
So I just had a lesson on loops and nested loops. My professor said that nested loops can help us do tasks such as knowing if we rolled 2 different matching pairs with 4 dices (4242) I'm a bit confused on how that would work.
So I started to work it out and this is what I was able to create.
public boolean 4matchDice(String dice){
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
}
}
I used boolean as the return as it will tell us whether or not we have 2 different matching pairs.
Thing is, what do I put in the the loops? That's what's confusing me the most.
Here's a solution I came up with, seems to be returning the correct outcome for all the test cases I ran.
public static boolean matchDice(String dice) {
char[] diceArray = dice.toCharArray();
int pairs = 0;
for (int i = 0; i < 4; i++) {
for (int j = i + 1; j < dice.length(); j++) {
if (diceArray[i] == diceArray[j]) {
diceArray[i] = 'X';
diceArray[j] = 'Y';
pairs++;
}
}
}
return (pairs > 1);
}
If you're only comparing two sets with two dice each, this is enough:
public boolean match4Dice(int first, int second, int third, int fourth) {
if ((first == third && second == fourth) || (first == fourth && second == third)) {
return true;
}
return false;
}
But if you're comparing 2 sets with any number of dice, the following algorithm would suit you better.
public boolean matchDice(String firstDiceSet, String secondDiceSet) {
// validate input, string must contain numbers from 1 - 6 only.
// lenghts of strings firstDiceSet & secondDiceSet must be equal
// works for any number of dice in each set.
// The dice only match if all numbers in the firstDiceSet all present in the secondDiceSet also.
// Let us count the matching numbers to check if this true.
int numberOfMatches = 0;
for (int i = 0; i < firstDiceSet.length(); i++) {
for (int j = 0; j < secondDiceSet.length(); j++) {
if (firstDiceSet[i] == secondDiceSet[j]) { // and not used
// increment number of matches
// mark secondDiceSet[j] as used, so that you do not count the same match twice.
// account for cases where firstDiceSet = "33" and the secondDiceSet = "35"
}
}
}
// your dice set match if the following condition is true
return (numberOfMatches == secondDiceSet.length());
}
Hi I just coded up a solution that will take "4242" as an input, although sindhu_sp's method is more practical i believe. I just wanted to show you another example to help your learning of java!
public static boolean fourMatchDice(String dice){
int match = 0;
for (int i = 0; i < dice.length(); i++){
for (int j = i+1; j < dice.length(); j++){
if (dice.toCharArray()[i] == dice.toCharArray()[j]){
System.out.println("does " + dice.toCharArray()[i] + " = " + dice.toCharArray()[j]);
match ++;
}
}
}
if(match == 2) *EDIT* //Change to (match >= 2) if 4 of the same pair is allowed.
return true;
return false;
}
public static void main(String[] args) {
System.out.println(fourMatchDice("4242"));
}
output:
does 4 = 4
does 2 = 2
true
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am defining an array to be a 121 array if all its elements are either 1 or 2 and it begins with one or more 1s followed by one or more 2s and end with same number of 1s that it begins with.
However i am not getting result while I was running my program.If program was ok I must get result 1 for given array {1,1,2,2,2,1,1}.
please help me.
public class OneTwoOne {
public static void main(String[] args) {
System.out.println(OneTwoOne.is121Array(new int[]{1, 1, 2, 2, 2, 1, 1}));
}
public static int is121Array(int[] a) {
int i, t1 = 0, t2 = 0, te = 0, tb = 0, tc = 0;
for (i = 0; i < a.length; i++) {//checking 1's and 2's in an array
if (a[i] == 1) {
t1 = 1;
}
if (a[i] == 2) {
t2 = 2;
}
}
for (i = 0; i < a.length; i++) {//counting number of 1's at begining of array
while (a[i] == 1) {
tb++;
}
break;
}
for (i = a.length; i >= 0; i--) {//counting number of 1's at end of array
while (a[i] == 1) {
te++;
}
break;
}
for (i = 0; i < a.length; i++) {//counting total number of 1's in an array
if (a[i] == 1) {
tc++;
}
}
if (t1 > 0 && t2 > 0 && t1 == t2 && te + tb == tc) {
//1's and 2's must be greater thna 0 and begining 1's and end 1's must be equal
//their sum is equal to total 1's in an array
return 1;
} else {
return 0;
}
}
}
You are using while loop instead of "if" clause, also the for loop limit is also unnecessarily long enough which is causing wrong result. I have made some changes in your method:
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
//StackOverflow question.
//http://stackoverflow.com/questions/32045039/array-elements-beginning-and-ending-with-1s-by-equal-number-at-both-end-and-oth/32045312#32045312
/* Name of the class has to be "Main" only if the class is public. */
class OneTwoOne {
static int i, t1 = 0, t2 = 0, te = 0, tb = 0, tc = 0;
public static void main(String[] args) {
int a [] = new int[]{1, 1, 2, 2, 2, 1, 1};
int retunValue = OneTwoOne.is121Array(a);
System.out.println("Number of 1s in starting ::"+te +"\n Number of 1s in the end ::"+ tb +"");
System.out.println("Return value :: "+retunValue );
}
public static int is121Array(int[] a) {
for (i = 0; i < a.length; i++) {//checking 1's and 2's in an array
if (a[i] == 1) {
t1 = 1;
}
if (a[i] == 2) {
t2 = 2;
}
}
int length = a.length;
for (i = 0; i < length/2; i++) {//counting number of 1's at begining of array
if (a[i] == 1) {
tb++;
}
}
for (i = a.length-1; i >= length/2; i--) {//counting number of 1's at end of array
if (a[i] == 1) {
te++;
}
}
if (te == tb)
return 1;
else
return 0;
}
}
You may run this program here. You may access the complete code here.
I've been stuck on this method for a couple of days now. This method checks to see if the roll of 5 dice == a small straight. It works for some numbers. If I roll a
1, 2, 4, 3, 6
it will work. However, if I roll a
1, 2, 4, 3, 3
it will not work. I think it's because of the duplicate 3 in there. I need to move it to the end somehow.
A small straight is when there are four consecutive die face values, such as 1, 2, 3, 4 or 3, 4, 5, 6. It can be in any order such as 2, 3, 1, 4
int counter = 0;
int score = 0;
boolean found = false;
Arrays.sort(die);
for (int i = 0; i < die.length - 1; i++)
{
if (counter == 3)
found = true;
if (die[i + 1] == die[i] + 1)
{
counter++;
}
else if (die[i + 1] == die[i])
{
continue;
}
else
{
counter = 0;
}
}
if (found)
{
score = 30;
}
else
{
score = 0;
}
return score;
}
The duplicate 3 is not what is throwing off the algorithm. The issue is that you check for the straight during the iteration AFTER it occurs. Thus, if the last die is part of the straight, it won't be recognized.
To fix this, move
if (counter == 3) found = true;
to the END of the loop. Should work.
EDIT: So it looks like this.
for (/*...*/) {
/* Everything else */
if (counter == 3) {
found = true;
break;
}
}
EDIT: First, if a small straight is three in a row, then you want to see if the counter gets to 2, not to 3. 3 would demand a four in a row.
Edit the start of the for loop as follows:
for (int i = 0; i < die.length ; i++)
{
if (counter == 2)
found = true;
if (i == die.length - 1) break;
//method continues here
Reasoning: I imagine that when you started coding this method, it was throwing IndexOutOfBoundsExceptions when it got to the last die in the array, tried to compare it to the nonexistant sixth die and died. So, you made the loop stop one short. But if it stops one short and the small straight is finished on the very last dice, then you never got into the loop again to confirm that the counter was 3 and a small straight had occured. By editing the start of the loop this way it goes all the way to the last element, checks and then breaks.
Alternatively, do one last check after the loop ends:
for (int i = 0; i < die.length - 1; i++)
{
if (counter == 2)
found = true;
if (die[i + 1] == die[i] + 1)
{
counter++;
}
else if (die[i + 1] == die[i])
{
continue;
}
else
{
counter = 0;
}
}
found = (counter == 2); // or counter >= 2 if you want larger straights to be found too
//continue method here
This should calculate the longest sequence:
int longestSequence(int[] a) {
Arrays.sort(a);
int longest = 0;
int sequence = 0;
for (int i = 1; i < a.length; i++) {
int d = a[i] - a[i - 1];
switch (d) {
case 0:
// Ignore duplicates.
break;
case 1:
sequence += 1;
break;
default:
if (sequence > longest) {
longest = sequence;
}
break;
}
}
return Math.max(longest, sequence);
}
You could add code such as
for (int i = 0; i < (die.length-1); i++)
{
if (die [i] == die[i+1])
{
die[i+1] =1;
}
}
Arrays.sort(die);
This will set the code for example from 1,2,3,3,4 to 1,1,2,3,4 so your code should then work.