Track Chosen Playing Card During Faro Shuffles - java

I'm building a Java app that tracks a chosen playing card during an "Out" faro shuffle. I've been a magician for a long time and this just seemed like a fun thing to do, and while I've seen apps/sites that will show you the order of an out faro after every shuffle, they don't specifically track a chosen card.
I sort of have a brute force method for every shuffle. I only have two shuffles completed, but the rest of the shuffles would basically be copy/paste, which goes against DRY, but every shuffle has a specific order, so I'm not sure how I could ensure that order remains the same after every iteration. Maybe store each iteration in its own list?
Oh and an out faro is when the cards are perfectly weaved, but the top and bottom cards remain the same. So a perfect 26/26 split and then a perfect weave.
If anyone has any better ideas let me know. The code isn't very pretty yet and I have refactoring to do.
package Tracker;
import java.util.ArrayList;
import java.util.List;
public class NewDeckOrder {
private ArrayList<String> bicycleDeckOrder;
public NewDeckOrder() {
String[] suitesFirstHalf = {"Hearts", "Clubs"};
String[] valuesFirstHalf = {"Ace", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King"};
String[] suitesSecondHalf = {"Diamonds", "Spades"};
String[] valuesSecondHalf = {"King", "Queen", "Jack", "10", "9",
"8", "7", "6", "5", "4", "3", "2", "Ace"};
bicycleDeckOrder = new ArrayList<>();
for (String deckFirstSuites : suitesFirstHalf) {
for (String deckFirstValues : valuesFirstHalf) {
bicycleDeckOrder.add(deckFirstValues + " of " +
deckFirstSuites);
}
}
for (String deckSecondSuites : suitesSecondHalf) {
for (String deckSecondValues : valuesSecondHalf) {
bicycleDeckOrder.add(deckSecondValues + " of " +
deckSecondSuites);
}
}
}
public ArrayList<String> getList() {
return bicycleDeckOrder;
}
#Override
public String toString() {
return "New Deck Order " + bicycleDeckOrder;
}
}
package Tracker;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class OutFaro {
private ArrayList<String> oneShuffle;
private ArrayList<String> twoShuffles;
private ArrayList<String> threeShuffles;
public ArrayList<String> getOneShuffle() {
return oneShuffle;
}
public void setOneShuffle(ArrayList<String> oneShuffle) {
this.oneShuffle = oneShuffle;
}
public ArrayList<String> firstShuffle(ArrayList<String> newDeckOrder)
{
ArrayList<String> first26 = new ArrayList<>();
ArrayList<String> last26 = new ArrayList<>();
for(int i = 0; i < newDeckOrder.size() - 26; i++) {
first26.add(newDeckOrder.get(i));
}
for(int j = 26; j < newDeckOrder.size(); j++) {
last26.add(newDeckOrder.get(j));
}
// One Shuffle
oneShuffle = new ArrayList<>();
for (int i = 0; i < first26.size(); i++) {
for (int j = 0; j < last26.size(); j++) {
oneShuffle.add(first26.get(i));
oneShuffle.add(last26.get(j));
i++;
}
}
return oneShuffle;
}
public ArrayList<String> getTwoShuffles() {
return twoShuffles;
}
public void setTwoShuffles(ArrayList<String> twoShuffles) {
this.twoShuffles = twoShuffles;
}
public ArrayList<String> secondShuffle(ArrayList<String>
firstShuffleResults) {
ArrayList<String> first26SecondShuffle = new ArrayList<>();
ArrayList<String> last26SecondShuffle = new ArrayList<>();
for(int i = 0; i < firstShuffleResults.size() - 26; i++) {
first26SecondShuffle.add(firstShuffleResults.get(i));
}
for(int j = 26; j < firstShuffleResults.size(); j++) {
last26SecondShuffle.add(firstShuffleResults.get(j));
}
// Second Shuffle
twoShuffles = new ArrayList<>();
for (int i = 0; i < first26SecondShuffle.size() - 1; i++) {
for (int j = 0; j < last26SecondShuffle.size() - 1; j++) {
twoShuffles.add(first26SecondShuffle.get(i));
twoShuffles.add(last26SecondShuffle.get(j));
i++;
}
}
return twoShuffles;
}
}
import Tracker.NewDeckOrder;
import Tracker.OutFaro;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
NewDeckOrder deckOrder;
// Bicycle new deck order
System.out.println("Current deck order:");
NewDeckOrder newDeckOrder = new NewDeckOrder();
System.out.println(newDeckOrder.toString());
// One out faro
System.out.println("\nPlease enter the card you wish to track: ");
Scanner input = new Scanner(System.in);
String cardToTrack = input.nextLine();
deckOrder = new NewDeckOrder();
int cardsPosition = 0;
ArrayList<String> temp = deckOrder.getList();
if (temp.contains(cardToTrack)) {
cardsPosition += temp.indexOf(cardToTrack) + 1;
}
System.out.println("\n" + cardToTrack + " starting position is " + cardsPosition + ".");
System.out.println("\n" + "Performing one out faro.");
OutFaro outFaro = new OutFaro();
String[] firstHalfSuites = new String[]{"Hearts", "Clubs"};
String[] firstHalfValues = new String[]{"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
String[] secondHalfSuites = new String[]{"Diamonds", "Spades"};
String[] secondHalfValues = new String[]{"King", "Queen", "Jack", "10", "9", "8", "7", "6", "5", "4", "3", "2", "Ace"};
outFaro.setOneShuffle(outFaro.firstShuffle(newDeckOrder.getList()));
// System.out.println("\n" + "First shuffle results: " + outFaro.getOneShuffle());
outFaro.setTwoShuffles(outFaro.secondShuffle(outFaro.getOneShuffle()));
int cardAfterOneShuffle = 0;
if (outFaro.getOneShuffle().contains(cardToTrack)) {
cardAfterOneShuffle += outFaro.firstShuffle(newDeckOrder.getList()).indexOf(cardToTrack) + 1;
}
System.out.println("\n" + "After one shuffle, your card is at number " + cardAfterOneShuffle);
int cardAfterTwoShuffles = 0;
// System.out.println("\n" + "Second shuffle results: " + outFaro.getTwoShuffles());
if (outFaro.getTwoShuffles().contains(cardToTrack)) {
cardAfterTwoShuffles += outFaro.getTwoShuffles().indexOf(cardToTrack) + 1;
}
System.out.println("\n" + "After two shuffles, your card is at number " + cardAfterTwoShuffles);
}
}

Alright, seems like every time I post on stackoverflow I end up finding the solution myself. Maybe it's just typing it out and working through it? Anyways, I found a much much much less convoluted way to do this recursively. I am actually proud of myself because I solved this 100% on my own so I guess my Java/programming knowledge is at a decent spot.
I don't think the code is 100% perfect yet, but far better than the "code vomit" solution I had before. Thank you to Meepo for kind of guiding me.
OutFaro Class that has the shuffling logic:
package Tracker;
import java.util.ArrayList;
public class OutFaro {
private ArrayList<String> shuffleResults;
private int shuffleCounter;
public ArrayList<String> getOneShuffle() {
return shuffleResults;
}
public ArrayList<String> outFaro(ArrayList<String> newDeckOrder, int numberOfFaros) {
shuffleResults = new ArrayList<>();
ArrayList<String> temp = new ArrayList<>();
while (shuffleCounter != numberOfFaros) {
for (int i = 0; i < newDeckOrder.size() - 26; i++) {
for (int j = 26; j < newDeckOrder.size(); j++) {
temp.add(newDeckOrder.get(i));
temp.add(newDeckOrder.get(j));
i++;
}
}
shuffleCounter++;
if (shuffleCounter == numberOfFaros) {
shuffleResults = temp;
} else {
outFaro(temp, numberOfFaros);
}
}
return shuffleResults;
}
#Override
public String toString() {
return "OutFaro{" +
"oneShuffle=" + shuffleResults +
'}';
}
}
New Deck Order class that builds the new deck:
package Tracker;
import java.util.ArrayList;
public class NewDeckOrder {
private ArrayList<String> bicycleDeckOrder;
public ArrayList<String> americanNewDeckOrder() {
String[] suitesFirstHalf = {"Hearts", "Clubs"};
String[] valuesFirstHalf = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
String[] suitesSecondHalf = {"Diamonds", "Spades"};
String[] valuesSecondHalf = {"King", "Queen", "Jack", "10", "9", "8", "7", "6", "5", "4", "3", "2", "Ace"};
bicycleDeckOrder = new ArrayList<>();
for (String deckFirstSuites : suitesFirstHalf) {
for (String deckFirstValues : valuesFirstHalf) {
bicycleDeckOrder.add(deckFirstValues + " of " + deckFirstSuites);
}
}
for (String deckSecondSuites : suitesSecondHalf) {
for (String deckSecondValues : valuesSecondHalf) {
bicycleDeckOrder.add(deckSecondValues + " of " + deckSecondSuites);
}
}
return bicycleDeckOrder;
}
public ArrayList<String> getBicycleDeckOrder() {
return bicycleDeckOrder;
}
public void setBicycleDeckOrder(ArrayList<String> bicycleDeckOrder) {
this.bicycleDeckOrder = bicycleDeckOrder;
}
#Override
public String toString() {
return "New Deck Order " + bicycleDeckOrder;
}
}
Client code:
import Tracker.NewDeckOrder;
import Tracker.OutFaro;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int cardAfterOneShuffle = 0;
Scanner input = new Scanner(System.in);
// Bicycle new deck order
System.out.println("Current deck order:");
NewDeckOrder newDeckOrder = new NewDeckOrder();
newDeckOrder.setBicycleDeckOrder(newDeckOrder.americanNewDeckOrder());
System.out.println(newDeckOrder.getBicycleDeckOrder().toString());
// User input
System.out.println("\nPlease enter the card you wish to track: ");
String cardToTrack = input.nextLine();
System.out.println("\nHow many out Faro's would you like to shuffle?");
int numberOfFaros = input.nextInt();
int cardsPosition = 0;
if (newDeckOrder.americanNewDeckOrder().contains(cardToTrack)) {
cardsPosition += newDeckOrder.americanNewDeckOrder().indexOf(cardToTrack) + 1;
}
System.out.println("\n" + cardToTrack + " starting position is " + cardsPosition + ".");
OutFaro outFaro = new OutFaro();
outFaro.outFaro(newDeckOrder.getBicycleDeckOrder(), numberOfFaros);
System.out.println("\n" + "After " + numberOfFaros + " shuffles the deck order is: " + outFaro.getOneShuffle());
if (outFaro.getOneShuffle().contains(cardToTrack)) {
cardAfterOneShuffle += outFaro.getOneShuffle().indexOf(cardToTrack) + 1;
}
System.out.println("\n" + "After " + numberOfFaros + " shuffles your card is at number " + cardAfterOneShuffle);
}
}

Related

java.lang.StringIndexOutOfBoundsException: String index out of range Error - Morse to English Java Code

I am working on a Morse Code to English java code (below) in which | in Morse stands for a blank space between letters and numbers, and a blank space in Morse stands in between 2 letters or digits. For ex., "to be" = "- --- | -... ." in Morse.
// Import Scanner.
import java.util.Scanner;
public class Project1_szhu1249322
{
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
System.out.println("Would you like to translate 'Morse Code' to English, or 'English' to Morse code? (Enter 'Morse Code' or 'English'.)");
String unit1 = input.nextLine();
System.out.println("Enter a string of " + unit1 + " characters (for English, numbers and letters, only): ");
String amountUnit1 = input.nextLine();
if (unit1.equals("Morse Code"))
toEnglish(amountUnit1);
else if (unit1.equals("English"))
toMorseCode(amountUnit1);
else
System.out.println("Invalid data. Enter 'Morse Code' or 'English' without the single quotes.");
}
public static void toMorseCode(String english)
{
// Declare variables, arrays, and strings.
int i = 0;
int l = english.length();
int i2 = 2 * i;
String[] lowerAlphabet = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","1", "2", "3", "4", "5", "6", "7", "8", "9", "0"};
String[] upperAlphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","1", "2", "3", "4", "5", "6", "7", "8", "9", "0"};
String[] morseCode = {".-", "-...", "-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..",".----","..---","...--","....-",".....","-....","--...","---..","----.","-----"};
morseCode[i] = lowerAlphabet[i];
StringBuilder morseBuilder = new StringBuilder();
// for loops and if statements for result.
for (i = 0; i < l; i++)
{
i2 = 2 * i;
if (english.charAt(i) != ' ')
morseBuilder.append(morseCode[i2]);
else
morseBuilder.append('|');
if (morseBuilder.charAt(i - 1) != ' ' && morseBuilder.charAt(i + 1) != 0)
morseBuilder.append(' ');
}
morseCode[i] = upperAlphabet[i];
// for loops and if statements for result.
for (i = 0; i < l; i++)
{
i2 = 2 * i;
if (english.charAt(i) != ' ')
morseBuilder.append(morseCode[i2]);
else
morseBuilder.append('|');
if (morseBuilder.charAt(i - 1) != ' ' && morseBuilder.charAt(i + 1) != 0)
morseBuilder.append(' ');
}
// Display results.
System.out.println("The corresponding Morse code is " + morseBuilder + ".");
}
public static void toEnglish(String morse)
{
// Declare variables, arrays, and strings.
int i = 0;
int l = morse.length();
int i2 = i / 2;
String[] lowerAlphabet = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","1", "2", "3", "4", "5", "6", "7", "8", "9", "0"};
String[] upperAlphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","1", "2", "3", "4", "5", "6", "7", "8", "9", "0"};
String[] morseCode = {".-", "-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..",".----","..---","...--","....-",".....","-....","--...","---..","----.","-----"};
morseCode[i] = upperAlphabet[i];
String english;
StringBuilder englishBuilder = new StringBuilder();
// for loops and if statements for result.
for (i = 0; i < l; i++)
{
i2 = i / 2;
if (morse.charAt(i) == '|')
{
englishBuilder.append(' ');
}
else
englishBuilder.append(morseCode[i2]);
}
morseCode[i] = lowerAlphabet[i];
// for loops and if statements for result.
for (i = 0; i < l; i++)
{
i2 = i / 2;
if (morse.charAt(i) == '|')
{
englishBuilder.append(' ');
}
else
englishBuilder.append(morseCode[i2]);
}
// Display results.
System.out.println("The corresponding English is " + englishBuilder + ".");
}
}
I am getting this error:
Would you like to translate 'Morse Code' to English, or 'English' to Morse code? (Enter 'Morse Code' or 'English'.)
English
Enter a string of English characters (for English, numbers and letters, only):
to be
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.AbstractStringBuilder.charAt(AbstractStringBuilder.java:237)
at java.lang.StringBuilder.charAt(StringBuilder.java:76)
at Project1_szhu1249322.toMorseCode(Project1_szhu1249322.java:42)
at Project1_szhu1249322.main(Project1_szhu1249322.java:16)
I do not understand why it is giving me this error message.
Also (question 2), what i2 value should I use? i / 2 only works for even i (when the first character is not a blank space. Help???
You failing on morseBuilder.charAt(i - 1) when i==0
Your code is have multiple risky point. You will get exception when i=0 at this code charAt(i - 1).
Also in function toEnglish after the loop done, you will have value of i will equal to l so that next line morseCode[i] = lowerAlphabet[i]; will cause the exception if your morse string is have length > the length of morseCode or lowerAlphabet
Use maps to map your letters "A", "B" and so on to their morse counter parts and vice versa for morse to english. This allows you to know what to use when converting between the two. Try the following and modify it to fit your needs.
public static void main(String[] args) throws IOException
{
String userInput = "Hello World";
String converted = ConvertEnglishToMorseCode(userInput);
System.out.println(userInput + " in Morse Code is " + converted);
System.out.println(converted + " in English is " + ConvertMorseCodeToEnglish(converted));
} //end main
public static String ConvertMorseCodeToEnglish(String input)
{
String[] upperAlphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","1", "2", "3", "4", "5", "6", "7", "8", "9", "0"};
String[] morseCode = {".-", "-...", "-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..",".----","..---","...--","....-",".....","-....","--...","---..","----.","-----"};
HashMap<String, String> morseToEnlgish = new HashMap<>();
for(int i = 0; i < upperAlphabet.length; i++)
morseToEnlgish.put(morseCode[i], upperAlphabet[i]);
String morseToEnglish = "";
String[] morseSplit = input.split(" ");
for(int i = 0; i < morseSplit.length; i++)
{
morseToEnglish += morseToEnlgish.containsKey(morseSplit[i]) ? morseToEnlgish.get(morseSplit[i]) : " ";
}
return morseToEnglish;
}
public static String ConvertEnglishToMorseCode(String input)
{
String[] upperAlphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","1", "2", "3", "4", "5", "6", "7", "8", "9", "0"};
String[] morseCode = {".-", "-...", "-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..",".----","..---","...--","....-",".....","-....","--...","---..","----.","-----"};
HashMap<String, String> englishToMorse = new HashMap<>();
for(int i = 0; i < upperAlphabet.length; i++)
englishToMorse.put(upperAlphabet[i], morseCode[i]);
String[] letters = input.toUpperCase().split("");
String englishToMorseWord = "";
for(int i = 0; i < letters.length; i++)
{
englishToMorseWord += englishToMorse.containsKey(letters[i]) ? englishToMorse.get(letters[i]) : "|";
if(i < letters.length - 1)
englishToMorseWord += " ";
}
return englishToMorseWord;
}
Output
Hello World in Morse Code is .... . .-.. .-.. --- | .-- --- .-. .-.. -..
.... . .-.. .-.. --- | .-- --- .-. .-.. -.. in English is HELLO WORLD
Note the slight differences in converting between the two. For English we split around "" to get every character by itself and use the mapping. For converting Morse to English we split around " " since I am assuming the letters in Morse code being given to you are in the format you are outputting when converting English words to Morse code, space separated. Lastly whenever we go from English to Morse Code and we don't have a mapping we fill in "|" and a " " when going from Morse Code to English.
Good Luck!

Transformation of two ArrayList

I've got a couple of ArrayList:
ArrayList a --> ["52", "52", "52", "52", "67", "67", "67", "67"]
ArrayList b --> ["1", "4", "5", "6", "3", "4", "5", "10"]
I want to transform them into:
ArrayList at --> ["52", "52", "67", "67"]
ArrayList bt --> ["1", "4 - 6", "3 - 5", "10"]
I know how to make b into bt, but I can't wrap my head around making a into at.
Algorith for making b into bt:
public static void main(String[] args) {
ArrayList<String> alist = new ArrayList<String>();
alist.add("1");
alist.add("4");
alist.add("5");
alist.add("6");
alist.add("3");
alist.add("4");
alist.add("5");
alist.add("10");
alist = groupByRange(alist);
}
static public ArrayList<String> groupByRange(ArrayList<String> alist) {
// ArrayList<String> to ArrayList<Integer>
/////////////////////////////////////////////////////////
ArrayList<Integer> alist_int = new ArrayList<Integer>();
for (String ident : alist) {
alist_int.add(Integer.parseInt(ident));
}
// ArrayList<Integer> to int[]
/////////////////////////////////////////////////////////
int[] arr = new int[alist_int.size()];
for (int i = 0; i < arr.length; i++) {
arr[i] = alist_int.get(i);
}
// Grouping by range (return ArrayList<String>)
/////////////////////////////////////////////////////////
int start, end;
end = start = arr[0];
ArrayList<String> alist_res = new ArrayList<String>();
for (int i = 1; i < arr.length; i++) {
if (arr[i] == (arr[i - 1] + 1)) {
end = arr[i];
} else {
if (start == end) {
alist_res.add(String.valueOf(start));
} else {
alist_res.add(String.valueOf(start) + " - " + String.valueOf(end));
}
start = end = arr[i];
}
}
if (start == end) {
alist_res.add(String.valueOf(start));
} else {
alist_res.add(String.valueOf(start) + " - " + String.valueOf(end));
}
for (String n : alist_res) {
System.out.println(n);
}
return alist_res;
}
I have method for You:
public List<String> groupByValue(List<String> listA) {
if (listA.isEmpty()) {
return Collections.emptyList();
}
final List<String> result = new ArrayList<>();
result.add(listA.get(0));
for (int actualIndex = 1; actualIndex < listA.size(); actualIndex++) {
if (actualIndex + 1 < listA.size() - 1 && !listA.get(actualIndex + 1).equals(listA.get(actualIndex))) {
result.add(listA.get(actualIndex));
actualIndex++;
}
if (actualIndex < listA.size() - 1 && !listA.get(actualIndex - 1).equals(listA.get(actualIndex))) {
result.add(listA.get(actualIndex));
}
if (actualIndex + 1 == listA.size()) {
result.add(listA.get(actualIndex));
}
}
return result;
}
This method has one parameter, is Your input list a. Then, we chcek list, and next, we add first value from a list. Next we check next values, and we have result on the end, it means at list.

Poker game hand evaluator arrays condition structure

I made up a quick poker game. It generates 5 random numbers and converts those numbers into actual cards values and symbols based on their value. However, I have problems when it comes to making the hand evaluation.
So far I only did the flush right as it's really easy but even then it's not perfect (it prints that the user has a flush 5 times... ) and I would really appreciate if someone could help me with the pair, two pair, three of a kind and straight. I could do the rest afterwards but I just need a heads-up on how to do those.
Thank you in advance for your help, here is the code :
package tests;
import java.util.*;
public class TESTS {
public static void main(String[] args) {
boolean[] pack = new boolean[52]; // Array to not generate the same number twice
int[] cards = new int[5]; //The 5 unique random numbers are stored in here.
String[] cardsvalues = new String[5]; // This will assign the card's value based on the random number's value
char[] cardssymbols = new char[5];//This will assign the card's symbol based on the random number's value
char symbols[] = {'♥', '♦', '♣', '♠'}; // possible symbols that the random number can take
String values[] = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"}; // possible values that the random number can take
Random give = new Random();
for (int i = 0; i < cards.length; i++) { // Gives 5 unique random numbers
do {
cards[i] = give.nextInt(52);
} while (pack[cards[i]]);
pack[cards[i]] = true;
System.out.println(cards[i]);
}
for (int i = 0; i < cards.length; i++) { // This converts the number to a card symbol based on the number's value
final int numOfSymbol = cards[i] / 13;
cardssymbols[i] = symbols[numOfSymbol];
}
for (int i = 0; i < cards.length; i++) { // This converts the number to an actual card value based on the number's value.
final int numOfValues = cards[i] % 13;
cardsvalues[i] = values[numOfValues];
}
for (int i = 0; i < cardssymbols.length; i++) { // Prints the actual cards once they are converted
System.out.print(cardssymbols[i]);
System.out.println(cardsvalues[i]);
}
for (int i = 0; i < cardsvalues.length; i++) { //Here is the problem, i have no idea on how to make the handevaluator ...
if (cardsvalues[i] == cardsvalues[i] + 1) {
System.out.println("PAIR !!!");
} else if (cardsvalues[i] == cardsvalues[i] + 1 && cardsvalues[i] == cardsvalues[i] + 2) {
System.out.println("TRIPS !!!");
} else if (cardssymbols[0] == cardssymbols[1] && cardssymbols[1] == cardssymbols[2] && cardssymbols[2] == cardssymbols[3] && cardssymbols[3] == cardssymbols[4]) {
System.out.println("FLUSHHH");
}
}
}
Hints:
To simplify testing for straights and sorting by highest card, it is easier to represent ranks by their indexes, and only translate them to the symbols for printing.
Using a Card object allows for clearer code.
The Java Collection framework has useful functions for shuffling, slicing and sorting.
My solution:
public class Test {
static final char[] suits = {'♥', '♦', '♣', '♠'};
static final String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
static class Card {
final int suit;
final int rank;
Card(int s, int r) {
suit = s;
rank = r;
}
#Override
public String toString() {
return suits[suit] + ranks[rank]; // or however you want the cards to be printed
}
}
public static void main(String[] args) {
List<Card> deck = new ArrayList<>();
for (int s = 0; s < suits.length; s++) {
for (int r = 0; r < ranks.length; r++) {
deck.add(new Card(s,r));
}
}
Collections.shuffle(deck);
List<Card> hand = deck.subList(0,5);
Collections.sort(hand, Comparator.comparing(c -> c.rank));
System.out.println("Your hand is: " + hand);
System.out.println(value(hand));
}
static String value(List<Card> hand) {
boolean straight = true;
boolean flush = true;
for (int i = 1; i < hand.size(); i++) {
straight &= hand.get(i - 1).rank + 1 == hand.get(i).rank;
flush &= hand.get(i - 1).suit == hand.get(i).suit;
}
if (straight && flush) {
return "Straight Flush from " + hand.get(4);
}
List<Run> runs = findRuns(hand);
runs.sort(Comparator.comparing(r -> -r.rank));
runs.sort(Comparator.comparing(r -> -r.length));
if (runs.get(0).length == 4) {
return "Four of a Kind: " + runs;
}
if (runs.get(0).length == 3 && runs.get(1).length == 2) {
return "Full House: " + runs;
}
if (straight) {
return "Straight from " + hand.get(4);
}
if (runs.get(0).length == 3) {
return "Three of a Kind: " + runs;
}
if (runs.get(1).length == 2) {
return "Two pair: " + runs;
}
if (runs.get(0).length == 2) {
return "Pair: " + runs;
}
return "High card: " + runs;
}
/** Represents {#code length} cards of rank {#code rank} */
static class Run {
int length;
int rank;
#Override
public String toString() {
return ranks[rank];
}
}
static List<Run> findRuns(List<Card> hand) {
List<Run> runs = new ArrayList<>();
Run run = null;
for (Card c : hand) {
if (run != null && run.rank == c.rank) {
run.length++;
} else {
run = new Run();
runs.add(run);
run.rank = c.rank;
run.length = 1;
}
}
return runs;
}
}
Example output:
Your hand is: [♣10, ♥J, ♦J, ♠K, ♥K]
Two pair: [K, J, 10]

Java create object array of numbers in string format

I'm writing a function for a program and I need to generate a list of numbers in an Object[]
For example.
Object[] possibilities = functionName(13);
Should generate
Object[] possibilities = {"1", "2", "3","4","5","6","7","8","9","10","11","12","13"};
How should I go about achieving this?
String functionName(int number){
StringBuilder str = new StringBuilder("{");
for(int i = 1; i <= number; i++){
str.append(Integer.toString(i)).append(", ");}
String string = str.toString().trim();
string = string.substring(0, str.length()-1);
string += "}";
return string;
}
This should give you the desired string and you just print it.
First, you need a method to print the results from your functionName (that's setting a goal post). Something like,
public static void main(String[] args) {
Object[] possibilities = functionName(13);
System.out.println(Arrays.toString(possibilities));
}
Then you might implement functionName with a basic for loop like
static Object[] functionName(int c) {
Object[] ret = new String[c];
for (int i = 0; i < c; i++) {
StringBuilder sb = new StringBuilder();
sb.append("\"").append(i + 1).append("\"");
ret[i] = sb.toString();
}
return ret;
}
And when I run the above I get (the requested)
["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"]
Try this method.
private Object[] function(int size) {
Object[] result = new String[size];
for (int i = 0; i < size; i++) {
result[i] = Integer.toString(i + 1);
}
return result;
}
}

incorrect display GraphView(android)

Sorry for my English. I do not know why I did not properly displays a message GraphView. Now in the graph below displays constantly 1,1,1,1 ... Though would have 1,2,3,4 ...And evaluation are all 1. A shows the graph as 10. Why is it, tell me please.
GraphViewSeriesStyle seriesStyle = new GraphViewSeriesStyle();
BarGraphView graphView = new BarGraphView(this, "test");
//Our vertical graph
graphView.setVerticalLabels(new String[] { "10", "9", "8", "7", "6",
"5", "4", "3", "2", "1" });
//listMarks its ArrayList whith Marks
String[] array = new String[ listMarks.size() ];
//add marks in array
for(int i = 0; i < listMarks.size(); i++) {
array[i] = "1";
}
graphView.setHorizontalLabels(array);
seriesStyle.setValueDependentColor(new ValueDependentColor() {
#Override
public int get(GraphViewDataInterface data) {
return Color.rgb((int)(22+((data.getY()/3))), (int)(160-((data.getY()/3))), (int)(134-((data.getY()/3))));
}
});
GraphViewData[] data = new GraphViewData[array.length];
for (int a = 0; a < array.length; a++) {
data[a] = new GraphView.GraphViewData(a, Double.parseDouble(array[a]));
}
GraphViewSeries series = new GraphViewSeries("aaa", seriesStyle, data);
graphView.setManualYMinBound(0);
graphView.addSeries(series);
LinearLayout layout = (LinearLayout) findViewById(R.id.subLayout);
layout.addView(graphView);
Change:
array[i] = "1";
to:
array[i] = ""+i;
in the following loop"
//add marks in array
for(int i = 0; i < listMarks.size(); i++) {
array[i] = "1";
}

Categories