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]
Related
I've made this poker program. It evaluates the hand and returns the results.
Everything works except my method to check for a straight. There is no error, but the method never returns true.
As a test, I have a while loop on the main (DeckOfCardsTest) to rerun the program until a straight is found.
Here is the code:
public class DeckOfCardsTest {
public static Card[] hand = new Card[5];
public static void main(String[] args) {
while(DeckOfCards.str == 0){
DeckOfCards myDeckOfCards = new DeckOfCards();
myDeckOfCards.shuffle(); // place Cards in random order
// print the hand dealt
for (int i = 0; i < 5; i++) {
// deal and display a Card
//System.out.printf("%-19s%n", myDeckOfCards.dealCard());
hand[i]= myDeckOfCards.dealCard();
if (i % 5 == 0) { // output a newline after every fifth card, incase dealing 2 hands in the future
System.out.println();
}
}//end of for loop
for(int i = 0; i < hand.length; i++){
System.out.println(""+ hand[i]);
}
DeckOfCards.Pair();//check hand for pair, 2 pair, 3 of a kind, four of a kind, or a full house
DeckOfCards.hasFlush(hand);//check hand for flush
System.out.println("\n\n\t" + DeckOfCards.Results() + "\n\n " + DeckOfCards.str);
//System.out.println(""+DeckOfCards.hasStraight(hand));
DeckOfCards.flushn=0;
}
} //end of main
}//end of class
Card Class
public class Card {
private final String face; // face of card ("Ace", "Deuce", ...)
private final String suit; // suit of card ("Hearts", "Diamonds", ...)
// two-argument constructor initializes card's face and suit
public Card(String cardFace, String cardSuit) {
this.face = cardFace; // initialize face of card
this.suit = cardSuit; // initialize suit of card
} //end of Card inilization
// return String representation of Card
public String toString() {
return face + " of " + suit;
}// endof toString method
public String getFace() {
return face;
}//end of getFace method
public String getSuit() {
return suit;
}//end of getSuit method
}//end of Class
Deck class
import java.security.SecureRandom;
public class DeckOfCards {
// random number generator
private static final SecureRandom randomNumbers = new SecureRandom();
private static final int NUMBER_OF_CARDS = 52; // constant # of Cards
public static int flushn = 0;
public static int str=0;
//private Card[] hand;
private Card[] deck = new Card[NUMBER_OF_CARDS]; // Card references
private int currentCard = 0; // index of next Card to be dealt (0-51)
// constructor fills deck of Cards
public DeckOfCards() {
String[] faces = {"Ace", "Deuce", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
String[] suits = {"Hearts", "Diamonds", "Clubs", "Spades"};
// populate deck with Card objects
for (int count = 0; count < deck.length; count++) {
deck[count] =
new Card(faces[count % 13], suits[count / 13]);
}
} //end of DeckOfCards constructor
public String getCard(){
String cCard = ("");
return cCard;
}
// shuffle deck of Cards with one-pass algorithm
public void shuffle() {
// next call to method dealCard should start at deck[0] again
currentCard = 0;
// for each Card, pick another random Card (0-51) and swap them
for (int first = 0; first < deck.length; first++) {
// select a random number between 0 and 51
int second = randomNumbers.nextInt(NUMBER_OF_CARDS);
// swap current Card with randomly selected Card
Card temp = deck[first];
deck[first] = deck[second];
deck[second] = temp;
}
} //end of shuffle method
// deal one Card
public Card dealCard() {
// determine whether Cards remain to be dealt
if (currentCard < deck.length) {
return deck[currentCard++]; // return current Card in array
}
else {
return null; // return null to indicate that all Cards were dealt
}
}//end of dealCard method
public static void hasFlush(Card[] hand) {
boolean isFlush = true;
String suit = hand[0].getSuit();
for(int i = 1; i < hand.length; i++) {
if(!(hand[i].getSuit().equals(suit))) {
isFlush = false;
}
}
if(isFlush){
flushn = 5;
}
}//end of flush evaluation
public static boolean hasStraight(Card[] hand) {
String[] faces = {"Ace", "Deuce", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
int minFace = 13;
for(int i = 0; i < hand.length; i++) {
int face = 13;
for(int j = 0; j < faces.length; j++) {
if(hand[i].getFace().equals(faces[j])) {
face = j;
}
}
if(face < minFace) {
minFace = face;
}
}
if(minFace > 7) {
return false;
}
boolean isStraight = true;
for(int i = minFace+1; i < minFace+hand.length; i++) {
boolean found = false;
for(int j = 0; j < hand.length; j++) {
if(hand[j].getFace().equals(faces[i])) {
found = true;
str++;
}
}
if(!found) {
str=0;
isStraight = false;
}
}
return isStraight;
}
public static int Pair(){
int pair = 0, done = 0, handcount = 1;
int pairCheck=0;
while (done <1){
for(int i = 0; i < 4; i++){
String tempCard = DeckOfCardsTest.hand[i].getFace();
for(int j=handcount; j < DeckOfCardsTest.hand.length; j++){
if(tempCard.equals(DeckOfCardsTest.hand[j].getFace()))
pair++;
}
handcount++;
}
pairCheck = pair;
done++;
}
return pairCheck;
}//endof Pair method
public static String Results(){
String results=("High Card");
int checkHand = 0;
if (Pair()>0 ){
switch (Pair()){
case 1:
results = ("Pair");
break;
case 2:
results = ("Two Pair!");
break;
case 3:
results = ("Three of a kind!");
break;
case 4:
results = ("Full House!");
break;
case 6:
results = ("FOUR of a kind!");
break;
default:
results = ("Somthing went terribly wrong, sorry");
break;
}
}//end of pairing results
if (flushn > 0){
results = ("Flush!");
}
if (str > 0){
results = ("Straight!");
}
return results;
}
}//end of Class
There is no error, but the method never returns true
This is not true. Your current hasStraight method is almost correct and does in fact return true/false correctly. The main issue you have is that your main loop uses the static variable str. There is a bug which does not reset str to zero correctly.
In short, there are two ways to address your problem:
1) Fix the issue with str
if (!found) {
str = 0;
isStraight = false;
break;
}
2) The main loop should use the boolean result of hasStraight instead of str.
boolean b = false;
while (!b) {
DeckOfCards myDeckOfCards = new DeckOfCards();
myDeckOfCards.shuffle(); // place Cards in random order
// print the hand dealt
for (int i = 0; i < 5; i++) {
// deal and display a Card
// System.out.printf("%-19s%n", myDeckOfCards.dealCard());
hand[i] = myDeckOfCards.dealCard();
if (i % 5 == 0) { // output a newline after every fifth card,
// incase dealing 2 hands in the future
System.out.println();
}
} // end of for loop
for (int i = 0; i < hand.length; i++) {
System.out.println("" + hand[i]);
}
DeckOfCards.Pair();// check hand for pair, 2 pair, 3 of a kind, four
// of a kind, or a full house
DeckOfCards.hasFlush(hand);// check hand for flush
System.out.println("\n\n\t" + DeckOfCards.Results() + "\n\n " + DeckOfCards.str);
b = DeckOfCards.hasStraight(hand);
System.out.println("Straight= " + b);
DeckOfCards.flushn = 0;
}
If I use either of these fixes, the main loop will loop until there is a straight.
Notes:
1. I believe the minFace check should be:
if (minFace > 8) {
return false;
}
Can an ace be high?
Ace code?
boolean hasAce = false;
for (int i = 0; i < hand.length; i++) {
if (hand[i].getFace().equals("Ace"))
hasAce = true;
}
// ... Current code ....
if (!isStraight && hasAce) {
isStraight = true;
for (int i = 9; i < 13; i++) {
boolean found = false;
for (int j = 0; j < hand.length; j++) {
if (hand[j].getFace().equals(faces[i])) {
found = true;
str++;
}
}
if (!found) {
str = 0;
isStraight = false;
break;
}
}
}
return isStraight;
How do I skip a number or a character same for two numbers or characters together or apart while those characters/numbers exist within a row of numbers or word
example (not lists):
I want to skip the number 3 (in any position) when I count from 2 to 14
the result would be
2,4,5,6,7,8,9,10,11,12,14
another would be skipping the number 31 in any combination where 3 and 1 come out as long as both exist
these two examples would apply for the characters also.
What I was doing was
for(int i = startingNum; i <= endingNum; i++){
if(i "has a" 3){
skip number;
}
else{
counter++;
}
}
combination of numbers
for(int i = startingNum; i <= endingNum; i++){
if((i "has a" 3) AND (i "has a " 1)){
skip number;
}
else{
counter++;
}
}
at the character one I'm completely lost...
One way would be to convert the number to a string and check if it contains that number as a substring:
for(int i = startingNum; i <= endingNum; i++) {
if (!String.valueOf(i).contains("3")) { // Here
counter++;
}
}
One of the approaches is using results of parsing, for example:
public static Integer isParsable(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return null;
}
}
...
import java.io.IOException;
public class NumChecker {
static String[] str = new String[]{"2", "4", "a", "sd", "d5", "6", "7", "8", "a1", "3", "10", "11", "12", "14"};
static int startingNum = 2;
static int endingNum = 10;
static int counter = 0;
static int mark = 3;
public static Integer isParsable(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return null;
}
}
public static void main(String[] args) throws IOException {
for (int i = startingNum; i <= endingNum; i++) {
Integer num = isParsable(str[i]);
if (num != null) {
if (num == mark) {
counter++;
}
}
}
System.out.println(counter);
}
}
OUTPUT:
1
I want to remove duplicate row in a 2d array . i tried the below code .but it is not working . please help me .
Input :
1,ram,mech
1,ram,mech
2,gopi,csc
2.gopi,civil
output should be :
1,ram,mech
2,gopi,csc
2.gopi,civil
Code :
package employee_dup;
import java.util.*;
public class Employee_dup {
public static void main(String[] args)
{
boolean Switch = true;
System.out.println("Name ID Dept ");
String[][] employee_t = {{"1","ram","Mech"},{"1","siva","Mech"},{"1","gopi","Mech"},{"4","jenkat","Mech"},{"5","linda","Mech"},{"1","velu","Mech"}};
int g = employee_t[0].length;
String[][] array2 = new String[10][g];
int rows = employee_t.length;
Arrays.sort(employee_t, new sort(0));
for(int i=0;i<employee_t.length;i++){
for(int j=0;j<employee_t[0].length;j++){
System.out.print(employee_t[i][j]+" ");
}
System.out.println();
}
List<String[]> l = new ArrayList<String[]>(Arrays.asList(employee_t));
for(int k = 0 ;k < employee_t.length-1;k++)
{
if(employee_t[k][0] == employee_t[k+1][0])
{
System.out.println("same value is present");
l.remove(1);
array2 = l.toArray(new String[][]{});
}
}
System.out.println("Name ID Dept ");
for(int i=0;i<array2.length;i++){
for(int j=0;j<array2[0].length;j++){
System.out.print(array2[i][j]+" ");
}
System.out.println();
}
}
}
class sort implements Comparator {
int j;
sort(int columnToSort) {
this.j = columnToSort;
}
//overriding compare method
public int compare(Object o1, Object o2) {
String[] row1 = (String[]) o1;
String[] row2 = (String[]) o2;
//compare the columns to sort
return row1[j].compareTo(row2[j]);
}
}
First I sorted the array based on column one ,then tried to remove duplicates by checking the first column elements and seconds column elements but it is not removing the required column but remove other columns.
You may give this solution a try:
public static void main(String[] args) {
String[][] employee_t = {
{"1","ram","Mech"},
{"1","ram","Mech"},
{"1","siva","Mech"},
{"1","siva","Mech"},
{"1","gopi","Mech"},
{"1","gopi","Mech"} };
System.out.println("ID Name Dept");
Arrays.stream(employee_t)
.map(Arrays::asList)
.distinct()
.forEach(row -> System.out.printf("%-3s%-7s%s\n", row.get(0), row.get(1), row.get(2)));
}
Output
ID Name Dept
1 ram Mech
1 siva Mech
1 gopi Mech
How it works: comparing arrays does rely on instance equality and not on comparing contained elements by equals. Hence converting each row of your 2D array into a List will enable you to compare lists, which takes equals of the elements contained into account.
The Java Stream API does provide a method distinct which relies on equals and will remove all duplicates for you.
Based on your code. Maybe it is not the BEST solution but it works.
public static void main(String[] args) {
System.out.println("Name ID Dept ");
// I added duplicated rows
String[][] inputArray = {
{ "1", "ram", "Mech" },
{ "1", "siva", "Mech" },
{ "1", "gopi", "Mech" },
{ "1", "gopi", "Mech" },
{ "4", "jenkat", "Mech" },
{ "5", "linda", "Mech" },
{ "1", "velu", "Mech" },
{ "1", "velu", "Mech" }
};
// I will add all rows in a Set as it doesn't store duplicate values
Set<String> solutionSet = new LinkedHashSet<String>();
// I get all rows, create a string and insert into Set
for (int i = 0 ; i < inputArray.length ; i++) {
String input = inputArray[i][0]+","+inputArray[i][1]+","+inputArray[i][2];
solutionSet.add(input);
}
// You know the final size of the output array
String[][] outputArray = new String[solutionSet.size()][3];
// I get the results without duplicated values and reconvert it to your format
int position = 0;
for(String solution : solutionSet) {
String[] solutionArray = solution.split(",");
outputArray[position][0] = solutionArray[0];
outputArray[position][1] = solutionArray[1];
outputArray[position][2] = solutionArray[2];
position++;
}
System.out.println("Name ID Dept ");
for (int i = 0; i < outputArray.length; i++) {
for (int j = 0; j < outputArray[0].length; j++) {
System.out.print(outputArray[i][j] + " ");
}
System.out.println();
}
}
I have posted what I think is a readable and easy to maintain solution.
I decided to use distinct from Stream which is part of Java 8
Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream. - https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#distinct--
Main.class
class Main {
public static void main(String[] args)
{
//Create a list of Employee objects
List<Employee> employeeList = new ArrayList<Employee>();
Employee e1 = new Employee(1, "ram", "mech");
Employee e2 = new Employee(1, "ram", "mech");
Employee e3 = new Employee(2, "gopi", "csc");
Employee e4 = new Employee(2, "gopi", "civil");
employeeList.add(e1);
employeeList.add(e2);
employeeList.add(e3);
employeeList.add(e4);
System.out.println("Before removing duplicates");
employeeList.stream().forEach(System.out::println);
//This is where all the magic happens.
employeeList = employeeList.stream().distinct().collect(Collectors.toList());
System.out.println("\nAfter removing duplicates");
employeeList.stream().forEach(System.out::println);
}
}
Output:
Before removing duplicates
Employee [valA=1, valB=ram, valC=mech]
Employee [valA=1, valB=ram, valC=mech]
Employee [valA=2, valB=gopi, valC=csc]
Employee [valA=2, valB=gopi, valC=civil]
After removing duplicates
Employee [valA=1, valB=ram, valC=mech]
Employee [valA=2, valB=gopi, valC=csc]
Employee [valA=2, valB=gopi, valC=civil]
Employee.class
//This is just a regular POJO class.
class Employee {
int valA;
String valB, valC;
public Employee(int valA, String valB, String valC){
this.valA = valA;
this.valB = valB;
this.valC = valC;
}
public Employee(Employee e) {
this.valA = e.valA;
this.valB = e.valB;
this.valC = e.valC;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + valA;
result = prime * result + ((valB == null) ? 0 : valB.hashCode());
result = prime * result + ((valC == null) ? 0 : valC.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if(obj instanceof Employee && ((Employee)obj).hashCode() == this.hashCode()){
return true;
}
return false;
}
#Override
public String toString() {
return "Employee [valA=" + valA + ", valB=" + valB + ", valC=" + valC + "]";
}
}
Pre Java - 8 solution. May not be the best way. But a quick solution which works..
String[][] records = {
{"1","ram","Mech"},
{"1","ram","Mech"},
{"1","gopi","csc"},
{"1","gopi","civil"} };
List<String[]> distinctRecordsList = new ArrayList<String[]>();
for(String[] record : records){
if(distinctRecordsList.size()>0){
boolean sameValue = false;
for(String[] distinctRecord : distinctRecordsList){
int distinctRecordFields = distinctRecord.length;
if(record.length==distinctRecordFields){
for(int k=0;k<distinctRecordFields;k++){
sameValue = record[k].equalsIgnoreCase(distinctRecord[k]);
if(!sameValue)
break;
}
}else
throw new Exception("Can't compare the records");
}
if(!sameValue)
distinctRecordsList.add(record);
}else if(distinctRecordsList.size()==0)
distinctRecordsList.add(record);
}
Object[] distRecObjects = distinctRecordsList.toArray();
String[][] distinctRecordsArray = new String[distRecObjects.length][];
int i=0;
for(Object distRecObject : distRecObjects){
distinctRecordsArray[i] = (String[]) distRecObject;
i++;
}
Contrary to some other answers I will try to explain what went wrong in your own code and how to fix it within your code (I agree very much with kkflf that an Employee class would be a huge benefit: it’s more object-oriented and it will help structure the code and give better overview of it).
The issues I see in your code are:
You are not removing the correct element when you detect a duplicate, but always the element at index 1 (the second element since indices count from 0). This isn’t trivial, though, because indices shift as you remove elements. The trick is to iterate backward so only indices that you are finished with shift when you remove an element.
You are using == to compare the first element of the subarrays you are comparing. If you wanted to compare just the first element, you should use equals() for comparison. However, I believe you want to compare the entire row so 2,gopi,csc and 2.gopi,civil are recognized as different and both preserved. Arrays.equals() can do the job.
You need to create array2 only after the loop. As your code stands, if no duplicates are detected, arrays2 is never created.
So your loop becomes:
for (int k = employee_t.length - 1; k >= 1; k--)
{
if (Arrays.equals(employee_t[k], employee_t[k - 1]))
{
System.out.println("same value is present");
l.remove(k);
}
}
array2 = l.toArray(new String[][]{});
This gives you the output you asked for.
Further tips:
Your comparator only compares one field in the inner arrays, which is not enough to guarantee that identical rows come right after each other in the sorted array. You should compare all elements, and also require that the inner arrays have the same length.
Use generics: class Sort extends Comparator<String[]>, and you won’t need the casts in compare()
According to Java naming conventions it should be class EmployeeDup, boolean doSwitch (since switch is a reserved word) and class Sort.
You are not using the variables Switch and rows; delete them.
I have wrote a solution for me. This may not be the best but it works.
public static String[][] removeDuplicate(String[][] matrix) {
String[][] newMatrix = new String[matrix.length][matrix[0].length];
int newMatrixRow = 1;
for (int i = 0; i < matrix[0].length; i++)
newMatrix[0][i] = matrix[0][i];
for (int j = 1; j < matrix.length; j++) {
List<Boolean> list = new ArrayList<>();
for (int i = 0; newMatrix[i][0] != null; i++) {
boolean same = true;
for (int col = 2; col < matrix[j].length; col++) {
if (!newMatrix[i][col].equals(matrix[j][col])) {
same = false;
break;
}
}
list.add(same);
}
if (!list.contains(true)) {
for (int i = 0; i < matrix[j].length; i++) {
newMatrix[newMatrixRow][i] = matrix[j][i];
}
newMatrixRow++;
}
}
int i;
for(i = 0; newMatrix[i][0] != null; i++);
String finalMatrix[][] = new String[i][newMatrix[0].length];
for (i = 0; i < finalMatrix.length; i++) {
for (int j = 0; j < finalMatrix[i].length; j++)
finalMatrix[i][j] = newMatrix[i][j];
}
return finalMatrix;
}
This method will return a matrix without any duplicate rows.
I am doing a Lotto application in a jForm/GUI in Netbeans with 3 rows of 5 numbers, and I don't want duplicates to be allowed on each line. To have one number on line 1 and the same on line 3 is OK, but to have those numbers on the same line is not OK.
The only way I can think of doing it that I know will work is to hard code it, and preferably, I don't want that.
I have tried:
boolean dup = false;
for (int k = 0; k < num[0].length){ //loop through columns
for (i = 0; i < num.length-1; i++) {
for (int j = i; j < inArray.length; j++){
if (num[k][i] == num[k][j]){
dup = true;
break;
}
}
}
}
and this:
public static boolean hasDuplicates(int [][] num) {
for (int row = 0; row < num.length; row++) {
int curRow = num[row];
Set set = Sets.newHashSet(Arrays.asList(curRow));
if (set.size() < curRow.length) {
return true;
}
}
return false;
}
I have also looked at other coding extensively and I can't get one that works.
The exact thing I'm trying to do is:
Get user's input for three lines of Lotto via text field, check each line for duplicates, print to a jLabel if it's a duplicate or leave the jLabel blank and run the rest of the code if there's no duplicates.
The current code I have is:
private void playBtnActionPerformed(java.awt.event.ActionEvent evt) {
num[0][0] = Integer.parseInt(line00Tf.getText());
num[0][1] = Integer.parseInt(line01Tf.getText());
num[0][2] = Integer.parseInt(line02Tf.getText());
num[0][3] = Integer.parseInt(line03Tf.getText());
num[0][4] = Integer.parseInt(line04Tf.getText());
num[1][0] = Integer.parseInt(line10Tf.getText());
num[1][1] = Integer.parseInt(line11Tf.getText());
num[1][2] = Integer.parseInt(line12Tf.getText());
num[1][3] = Integer.parseInt(line13Tf.getText());
num[1][4] = Integer.parseInt(line14Tf.getText());
num[2][0] = Integer.parseInt(line20Tf.getText());
num[2][1] = Integer.parseInt(line21Tf.getText());
num[2][2] = Integer.parseInt(line22Tf.getText());
num[2][3] = Integer.parseInt(line23Tf.getText());
num[2][4] = Integer.parseInt(line24Tf.getText());
duplicateLbl.setText("");
LottoPhase1 p1 = new LottoPhase1();
p1.setNum(num);
p1.createSecret();
secret = p1.getSecret();
p1.computeCheckInput();
correctL1 = p1.getCorrectL1();
correctL2 = p1.getCorrectL2();
correctL3 = p1.getCorrectL3();
//prints secret to output
System.out.println("Phase 1 Main Secret: " + Arrays.toString(secret));
System.out.println();
displayResults0Lbl.setText(Integer.toString(secret[0]) + ", " + Integer.toString(secret[1]) + ", " + Integer.toString(secret[2]) + ", " + Integer.toString(secret[3]) + ", " + Integer.toString(secret[4]));
matched1NumLbl.setText(Integer.toString(correctL1));
matched2NumLbl.setText(Integer.toString(correctL2));
matched3NumLbl.setText(Integer.toString(correctL3));
}
public static boolean hasDuplicates(int[][] num)
{
boolean hasDuplicate = false;
// for each line in num
for(int[] line : num)
{
// for every number in the row
for(int i = 0; i < line.length && !hasDuplicate; i++)
{
// for every number in the row
for(int j = 0; j < line.length; j++)
{
// if we are not comparing the same number
if(i != j)
{
// check for equality
if(line[i] == line[j])
{
hasDuplicate = true; // we have found a duplicate
break; // no need to keep checking; break the loop and return
}
}
}
}
}
return hasDuplicate;
}
The second method has a couple of errors, for instance,
int curRow = num[row];
Should actually be:
int[] curRow = num[row];
Also, you appear to be using Sets, which probably comes from some library you're using (Guava, Google Common, etc.). Assuming you were not using any library, you could change your code to something similar to:
public static boolean hasDuplicates(int [][] num) {
for (int[] curRow : num) {
Set<Integer> set = new HashSet<>();
for (int n : curRow) {
if (!set.add(n)) {
return true;
}
}
}
return false;
}
If you're using Java 8, one way to remove the second for loop is by using a Stream:
public static boolean hasDuplicates(int [][] num) {
for (int[] curRow : num) {
Set<Integer> set = IntStream.of(curRow).boxed().collect(Collectors.toSet());
if (set.size() < curRow.length) {
return true;
}
}
return false;
}
Other alternatives to the Stream can be found in threads like these.
Testing with the following input produces what I think you would expect:
int[][] testA = {{0,1,2,3,4}, {0,1,2,3,4}, {0,1,2,3,4}}; //false
int[][] testB = {{0,1,2,3,4}, {0,2,2,3,4}, {0,1,2,3,4}}; //true
int[][] testC = {{0,1,2,3,4}, {0,1,2,3,4}, {0,4,3,3,4}}; //true
int[][] testD = {{0,1,2,3,4}, {5,6,7,8,9}, {10,11,12,13,14}}; //false
I am keen to sort only numeric elements that are in String array. I am doing it in java. Please help me to solve this Problem.
Here is my Problem
For the given set of characters, choose integers only and sort them in descending order and put in their position leaving other characters position intact.
The change is position should only be of integers not of other characters.
Sample Input:-
d,1,4,c,9,6
109,87,911,b,645
77,19,#,.,95
8,99,14,2,5,6,49
Sample Output:-
Case #1: d,9,6,c,4,1
Case #2: 911,645,109,b,87
Case #3: 95,77,#,.,19
Case #4: 99,49,14,8,6,5,2
Thank you to all viewer. Please would you all help me to solve this problem in Java
Here is my Code, I have tried So far.
import java.util.Arrays;
import java.util.Iterator;
import java.util.ArrayList;
class alphaNumeric {
public static void main(String a[]) {
String s1[] = new String[9];
ArrayList l_numList = new ArrayList();
ArrayList l_strList = new ArrayList();
s1[0] = "1000.1";
s1[1] = "100";
s1[2] = "xBC100";
s1[3] = "XBB100";
s1[4] = "TEST";
s1[5] = "AYZ2100";
s1[6] = "99";
s1[7] = "90";
s1[8] = "1000";
System.out.print("Before sorting, numbers are ");
for(int i = 0; i < s1.length; i++)
{
System.out.print(s1[i]+" ");
}
System.out.println();
for (int i = 0; i < s1.length; i++) {
if (isNumber(s1[i])) {
l_numList.add(s1[i]);
} else {
l_strList.add(s1[i]);
}
}
Object[] l_objArray = (Object[]) l_numList.toArray();
int l_intArray[] = new int[l_objArray.length];
for (int i = 0; i < l_objArray.length; i++) {
l_intArray[i] = Integer.parseInt((String) l_objArray[i]);
}
Arrays.sort(l_intArray);
for (int i = 0; i < l_intArray.length; i++) {
System.out.println("after Numsort: " + l_intArray[i]);
}
System.out.print("After sorting, numbers are ");
for(int i = 0; i < l_intArray.length; i++)
{
System.out.print(l_intArray[i]+" ");
}
Object[] l_strArray = (Object[]) l_strList.toArray();
Arrays.sort(l_strArray);
for (int i = 0; i < l_strArray.length; i++) {
System.out.println("after Strsort: " + l_strArray[i]);
}
}
static boolean isNumber(String s) {
String validChars = "0123456789";
boolean isNumber = true;
for (int i = 0; i < s.length() && isNumber; i++) {
char c = s.charAt(i);
if (validChars.indexOf(c) == -1) {
isNumber = false;
} else {
isNumber = true;
}
}
return isNumber;
}
}
I couldn't figure out what you were trying to do, but here's how I'd do it
Extract a List of only the Integers AND create List of indexes at which they occur in original array
Sort that List using standard reverse sort
Put sorted List values back into the original array, using index List
Working example
public class SortOnlyNumbers {
public static void main(String[] args) {
sortOnlyNumbers(new String[] { "d", "1", "4", "c", "9", "6" });
sortOnlyNumbers(new String[] { "109", "87", "911", "b", "645" });
sortOnlyNumbers(new String[] { "77", "19", "#", ".", "95" });
sortOnlyNumbers(new String[] { "8", "99", "14", "2", "5", "6", "49" });
}
private static void sortOnlyNumbers(String[] array) {
List<Integer> indexes = new ArrayList<Integer>();
List<Integer> numbers = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++) {
try {
numbers.add(Integer.parseInt(array[i]));
indexes.add(i);
} catch (NumberFormatException e) {
// don't care
}
}
Collections.sort(numbers, Collections.reverseOrder());
for (int i = 0; i < numbers.size(); i++) {
array[indexes.get(i)] = String.valueOf(numbers.get(i));
}
System.out.println(Arrays.toString(array));
}
}
Output
[d, 9, 6, c, 4, 1]
[911, 645, 109, b, 87]
[95, 77, #, ., 19]
[99, 49, 14, 8, 6, 5, 2]