I'm trying to create a method that would return largest set of cards which has neighbors. For example if I have list<RANK> rankList = [FIVE, QUEEN, KING, ACE, TEN]
it would return [KING, ACE, QUEEN]
. I haven't fully implemented it, but I got that part with splits one set in multiple smaller sets.
private boolean isStraight(List<Card> cards) {
Set<RANK> rankList = cards.stream()
.map(Card::getRank)
.distinct()
.collect(Collectors.toSet());
List<Set<RANK>> subSets = new ArrayList<>();
for(RANK rank : rankList) {
int currRankValue = rank.getValue();
RANK prevRank = RANK.getRank(currRankValue - 1);
RANK nextRank = RANK.getRank(currRankValue + 1);
if(!subSets.stream().anyMatch(set -> set.contains(rank))) {
Set<RANK> newSet = new HashSet<>();
newSet.add(rank);
subSets.add(newSet);
}
subSets.stream()
.filter(set -> (set.contains(prevRank) || set.contains(nextRank)))
.forEach( set -> set.add(rank));
}
System.out.print(subSets);
return false;
}
Card.java:
public static enum RANK {
NONE(0),
TWO(2), THREE(3), FOUR(4), FIVE(5),
SIX(6), SEVEN(7), EIGHT(8), NINE(9),
TEN(10), JACK(11), QUEEN(12), KING(13), ACE(14);
private final int value;
private RANK(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public static RANK getRank(int value) {
for(RANK r : RANK.values() ) {
if (r.getValue() == value)
return r;
}
return NONE;
}
}
And before I check if there is 5 or more cards that could make a straight I have combine sub sets which has at least one common value. How can I do it? I'cant think of anything that wouldn't involve many loops.
EDITED
Added whole Card.java:
ppackage deck;
public class Card implements Comparable {
public static enum SUIT {
SPADES,
HEARTS,
CLUBS,
DIAMONDS
}
public static enum RANK {
NONE(0),
TWO(2), THREE(3), FOUR(4), FIVE(5),
SIX(6), SEVEN(7), EIGHT(8), NINE(9),
TEN(10), JACK(11), QUEEN(12), KING(13), ACE(14);
private final int value;
private RANK(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public static RANK getRank(int value) {
for(RANK r : RANK.values() ) {
if (r.getValue() == value)
return r;
}
return NONE;
}
}
private final RANK rank;
private final SUIT suit;
public Card(RANK rank, SUIT suit) {
this.rank = rank;
this.suit = suit;
}
public RANK getRank() {
return rank;
}
public SUIT getSuit() {
return suit;
}
@Override
public String toString() {
return "Card{" +
"rank=" + rank +
", suit=" + suit +
'}';
}
@Override
public int compareTo(Object that) {
return this.rank.getValue() - ((Card) that).rank.getValue();
}
}
EDITED
Added solution with loops: adding this before return in the method.
for(int index = 0; index < subSets.size(); index++) {
for(int index2 = 1; index2 < subSets.size(); index2++) {
if(!Collections.disjoint(subSets.get(index), subSets.get(index2)) && index != index2) {
subSets.get(index).addAll(subSets.remove(index2));
index2--;
}
}
}