Created
February 2, 2012 03:15
-
-
Save ericlemerdy/1721193 to your computer and use it in GitHub Desktop.
Cannot decide: guava or plain old for loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public Boolean hasStraightFlush_plainJava() { | |
Suit expectedSuit = cards.get(0).getSuit(); | |
int minValue = cards.get(0).getValue().ordinal(); | |
for (int i = 1; i < 5; i++) { | |
Card card = cards.get(i); | |
if (card.getValue().ordinal() != minValue + i) { | |
return false; | |
} | |
if (card.getSuit() != expectedSuit) { | |
return false; | |
} | |
} | |
return true; | |
} | |
public Boolean hasStraightFlush_guava() { | |
Suit expectedSuit = cards.get(0).getSuit(); | |
int minValue = cards.get(0).getValue().ordinal(); | |
ArrayList<String> expectedFlush = Lists.newArrayList(); | |
for (int i = 0; i < 5; i++) { | |
expectedFlush.add((minValue + i) + ":" + expectedSuit); | |
} | |
String expected = on(',').join(expectedFlush); | |
String actual = on(',').join(transform(cards, new Function<Card, String>() { | |
public String apply(Card input) { | |
return input.getValue().ordinal() + ":" + input.getSuit().name(); | |
} | |
})); | |
return expected.equals(actual); | |
} |
I have another proposal built on the all
(Enumerable#all?)
And all
predicate is given each element in the list, until predicate is false ...
It depends on the struct at hand, and if my list is [1,2,3,4,5] then I'm toasted ! I have to build a list of element that carries a previous
erl
So given L = [4,5,6,7,8]
, I build a list of pairs {Previous, Current}
for the tail list ([5,6,7,8]
), then apply all
with predicate : Previous + 1 == Current
Now, that is allocating 2 lists in the course (seq, comprehension) ... so I dislike it
19> Flush = fun(L) -> lists:all(fun({Previous,Current}) -> Previous+1==Current end, [ {lists:nth(N-1, L), lists:nth(N, L)} || N <- lists:seq(2, length(L)) ]) end.
#Fun<erl_eval.6.13229925>
20> Flush([5,6,7,9]).
false
21> Flush([5,6,7,8]).
true
Here is a function that does not allocate more lists
flush(L) ->
[Head | Tail] = L,
flush(Head, Tail).
flush(_, []) ->
true;
flush(Previous, [Current | Tail]) ->
(Previous + 1 == Current) and flush(Current, Tail).
:)
WDYT?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How would you write it in a "natural langage" ?
And how would you do it in another langage ?
Say ruby ?
loop and early return
reduce and early return
A loop is enough ?
(might look later in erl and java...)