C
C#2y ago
Triufelis

❔ Ace value of 1 or 11

I am writing a blackjack game. I have written a method to calculate the amount of "score" the player has. But the method has two separate foreaches. That is not necessarily how a method should be coded. Is there a way to remove one of the foreaches? so it fits the definition of a method?
20 Replies
Angius
Angius2y ago
uh A method can have 69 foreaches nested inside of 420 wheres It's still a method (also, why virtual..?)
Anton
Anton2y ago
looks ok as is
VIPER
VIPER2y ago
Can u not just use an else Oh nvm Ye that’s fine
Tvde1
Tvde12y ago
you could use an else to make it more performant count the number of aces in the one loop and in the second loop, loop for that count
Triufelis
Triufelis2y ago
cause its inside an abstarct class. Im just practising all i learn. Putting it all to use. Well at uni, they teach us that there cant be 2 seperate fors or foreaches as that goes agains the principles of OOP. Nested fors and foreaches are good.
Angius
Angius2y ago
They're full of shit, then
Anton
Anton2y ago
what
Angius
Angius2y ago
But no worries Most schools are
Triufelis
Triufelis2y ago
Well the logic is that one method should do only one thing Seems unreasonable But it is what it is 🙂
Anton
Anton2y ago
you're misinterpreting what they said
Angius
Angius2y ago
I mean, it is doing one thing
Anton
Anton2y ago
most likely
Angius
Angius2y ago
And uses two loops to achieve that
Triufelis
Triufelis2y ago
Idk. If the loops are nested it is alright. But if they are seperate ones. Like the ones i sent before. Then it is not alright. Maybe i misinterpreted what the teaches wanted to say. But the fact still remains
Angius
Angius2y ago
It is perfectly fine Although, I guess, you could merge those loops into one
Amos
Amos2y ago
I hate this 😅
HimmDawg
HimmDawg2y ago
To get back to the question: If you do
foreach(var c in CardsInHand)
{
if(c.Rank == "A")
{
// ...
}
else
{
// ...
}
}
foreach(var c in CardsInHand)
{
if(c.Rank == "A")
{
// ...
}
else
{
// ...
}
}
then you'll get one loop that does what both of these loops do
Anton
Anton2y ago
no, they gather the counts in the first loop, look closer
Amos
Amos2y ago
You could replace the first foreach with this.
var count = CardsInHand.Where(card => card.Rank is not "A").Sum(cardSum => cardSum.RankValue);
var count = CardsInHand.Where(card => card.Rank is not "A").Sum(cardSum => cardSum.RankValue);
Though, it's just doing the same thing, just a little neater imo.
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.