Coding challenge
Write a program that will create a standard deck of cards, shuffle it, and deal 5 cards to 5 players. Use any language you like.
GO GO GO
Coding challenge
Write a program that will create a standard deck of cards, shuffle it, and deal 5 cards to 5 players. Use any language you like.
GO GO GO
Other urls found in this thread:
code.jsoftware.com
random.org
gist.github.com
en.wikipedia.org
twitter.com
not your personal homework solving force.
Nah I came up with the idea after seeing pic related.
quite easy with java, thanks to Colletions.shuffle
This uses the fisher-yates algorithm, nice.
package main
import(
"fmt"
"math/rand"
"time"
)
type Player struct {
Name string
HeldCards []Card
}
func InitPlayer(name string) Player {
var gamer Player
gamer.Name = name
gamer.HeldCards = make([]Card, 0)
return gamer
}
type Card struct {
CardName string
CardColor string
}
func InitDeck() []Card {
var Deck = make([]Card, 0)
for _, Color := range []string{"Clubs", "Diamonds", "Hearts", "Spades"} {
for _, Type := range []string{"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"} {
Deck = append(Deck, Card{Type, Color})
}
}
return Deck
}
func shuffle(c []Card) {
r := rand.New(rand.NewSource(time.Now().Unix()))
for len(c) > 0 {
n := len(c)
randIndex := r.Intn(n)
c[n-1], c[randIndex] = c[randIndex], c[n-1]
c = c[:n-1]
}
}
func dealCards(c []Card, p []Player) []Card {
for i := 0; i < 5; i++ {
for x := 0; x < len(p); x++ {
lenght := len(c)-1
p[x].HeldCards = append(p[x].HeldCards, c[lenght])
c = c[:lenght]
}
}
return c
}
func main() {
deckOfCards := InitDeck()
var players = make([]Player, 0)
for _, name := range []string{"foo", "bar", "baz", "spam", "spagett"} {
players = append(players, InitPlayer(name))
}
shuffle(deckOfCards)
deckOfCards = dealCards(deckOfCards, players)
fmt.Println(players)
fmt.Println(deckOfCards, len(deckOfCards))
}
Powershell. Not exactly pretty and the use of global is certainly hacky but it werkz as a one liner.
$global:i = 0;'','','',''|%{ $suite = $_; 2..10 + 'J','Q','K','A'|%{ "$suite$_" } }|sort {get-random}|group {$global:i % 5 + 1; $global:i++}|%{ "Player {0} cards: {1}" -f $_.name,$($_.group[0..4] -join ", ") }
>java
please do the needful sir
Shit it seems the characters for suites are not allowed in a comment. Reposting it without formatting:
$global:i = 0;'','','',''|%{ $suite = $_; 2..10 + 'J','Q','K','A'|%{ "$suite$_" } }|sort {get-random}|group {$global:i % 5 + 1; $global:i++}|%{ "Player {0} cards: {1}" -f $_.name,$($_.group[0..4] -join ", ") }
okay something is fishy. I can't post pic related characters, they probably get filtered.
I am at yo mama house
Based Python
from collections import deque
import random
class Deck():
def __init__(self):
suits = ['clubs', 'diamonds', 'hearts', 'spades']
values = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
self._cards = deque([(v, s) for v in values for s in suits])
self._dealt = deque()
def shuffle(self):
random.shuffle(self._cards)
def deal(self) -> [str, str]:
"""Deal one card from top of deck"""
popped = self._cards.pop()
self._dealt.appendleft(popped)
return popped
def collect(self):
"""Place dealt cards on top of deck"""
self._cards.extend(self._dealt)
self._dealt = []
def main():
deck = Deck()
deck.shuffle()
for player in range(5):
print(f'Player {player + 1}: ', end='')
print([deck.deal() for _ in range(5)])
if __name__ == '__main__':
main()
def deal(self) -> [str, str]:
can someone explain this?
Also I really need to look into the collections library. Seems really useful.
That's the return type of the function. It means it returns a pair of strings. I really should have imported Typing and Tuple and then done -> Tuple[str, str]
It doesnt change anyhting programmatically it's jsut to indicate to a linter the return type
It's a function annotation. It denotes the expected output of the return statement (e.g. ['A','clubs']). In th is program itself I don't think it is functional and seems like OP is just habituated to use it/show his powerlevel.
I'm not doing your homework
I'm habituated to use it cause at work it makes things easier to read
import System.Random
data CardType = Heart | Tile | Clover | Pike
deriving (Show)
data CardValue = Ace | One | Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King
deriving (Show)
data Card = Card CardType CardValue
deriving (Show)
data Deck = Deck [Card]
deriving (Show)
cardTypes = [Heart, Tile, Clover, Pike]
cardValues = [Ace, One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King]
initDeck :: Deck
initDeck = let
createCard (a, b) = Card a b
allcardsoftype t = zip (repeat t) cardValues
cardscombined = concat $ map allcardsoftype cardTypes
in
Deck $ map createCard $ cardscombined
-- TODO: replace me with better algorithm / library function
shuffle x = if length x < 2 then return x else do
i
Checkmate, atheists
>5 5$(25?52){,(
Which schizo language is this
>hardcoded amount of players
That also falls under state, which I didn't bother doing.
>todo: use state
val deck = for(c
brainlet here
what lang is dis?
go
it is a bad meme language
Thanks. I will now proceed not to check it out as a consequence of your feedback.
Also for Php. You ca. Just shuffle an array.
And does everyone here care about the naming of the cards. It doesnt matter if you output Heart 8 or just a number, since all cards are unique anyway and you could do the mapping later.
for ( X < >.pick(25)).rotor(5) {.say}
Jow Forums ate my unicode
for ( X .pick(25)).rotor(5) {.say}
> def main():
> ...
> main()
get the java programming gremlins out of your head, pajeet
What language is this even?
perl 6
She has a long midface
Does anyone else wear corduroy trousers? I have a green pair that I wear with my dark blue denim jacket, it looks fantastic.
why
...
am i cool now guise
from random import randint
def shuffle(arr):
n=len(arr)-1
for i in range(len(arr)):
swap(arr, n, randint(0,n))
n=n-1
def swap(arr,i,j):
arr[i],arr[j] = arr[j], arr[i]
arr = [1,2,3,4,5,6,7]
shuffle(arr)
for i in range(len(arr)):
print(arr[i])
Is that the blacked girl?
what colour is her pubes?
import random
game = {"deck":[(("ace","jack","king","queen")[x]+" of "+("spades","clubs","hearts","diamonds")[y]) for x in range(0,4) for y in range(0,4)] + [(str(x)+" of "+ ("spades","clubs","hearts","diamonds")[y]) for x in range(2,11) for y in range(0,4)],"players":[[],[],[],[],[]]}
random.shuffle(game["deck"])
while len(game["players"][len(game["players"])-1]) < 5:
for x in range(0,len(game["players"])):
game["players"][x].append(game["deck"].pop())
Probably trolling but LINK
# Write a program that will create a standard deck of cards, shuffle it, and deal 5 cards to 5 players. Use any language you like.
defmodule Cards do
def play_cards do
draw()
|> shuffle()
|> Enum.chunk(5)
|> Enum.take(5)
end
def draw do
for type "Queen #{type}"
13 -> "King #{type}"
n -> "#{n} #{type}"
end
end
end
end
def shuffle(list) do
list
|> List.flatten()
|> Enum.shuffle()
end
end
IO.inspect(Cards.play_cards())
# [
# ["8 of Hearts", "1 of Diamonds", "3 of Clubs", "Queen of Clubs",
# "4 of Spades"],
# ["3 of Hearts", "9 of Hearts", "9 of Diamonds", "Jack of Clubs",
# "5 of Hearts"],
# ["Jack of Hearts", "10 of Clubs", "3 of Spades", "1 of Hearts",
# "Queen of Hearts"],
# ["2 of Clubs", "Queen of Diamonds", "9 of Clubs", "7 of Spades",
# "10 of Spades"],
# ["8 of Clubs", "5 of Clubs", "Jack of Spades", "6 of Diamonds", "6 of Spades"]
# ]
The draw function is pretty shit and you could probably clean it up massively but I didn't look too much into it.
No it's a pic some guy took of a random girl on the Stockholm metro.
import pycards as cards
cards.shuffle
players=[]
for p in range(0,4):
c =cards.deal(5)
players.append(c)
print("python wins again you fucking bloated programmers!")
Was sauce ever found?
Possibly but as far as I know the original is just a pic some guy took and probably posted on an imageboard.
Source(s): my ass though so I might very well be wrong.
>sweden
shes probably dead now raped by some afrikan rape gang
she's very similar to the blacked meme from Jow Forums.
>import pycards as cards
>using external resources
why not just write something like this then
(new CardService)->giveCardsToPlayers(5, 5);
Seems like they made perl nicer, then.
let numPlayers = 5;
let cardsPerPlayer = 5;
const houses = ["Hearts", "Clubs", "Diamonds", "Spades"];
const cardValues = ["2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"]
deck = [];
players = [];
// Build deck
for (let house of houses)
for (let cardValue of cardValues)
deck.push([house, cardValue])
// Shuffle deck
deck.sort(function(a, b){return 0.5 - Math.random()});
// Make player hands
for (let i=0; i
what did she mean by this face?
Install Gentoo
You have a small penis.
I went a little overkill.
import random, sequtils
const
playerCount = 5
nDeals = 5
type
Suit {.pure.} = enum
Heart, Diamond, Club, Spade
Card = object
suit: Suit
value: range[1..13]
Player = ref object
hand: seq[Card]
proc newDeck: seq[Card] =
result = @[]
for s in Suit.low..Suit.high:
for v in 1..13:
result.add Card(suit: s, value: v)
proc newPlayerArr: array[playerCount, Player] =
for i in 0..(playerCount - 1):
result[i] = Player(hand: newSeq[Card]())
proc deal(deck: var seq[Card], cards: var seq[Card]): bool =
if deck.len>= playerCount:
for i, _ in cards:
cards.add deck[deck.high]
deck.delete(deck.high)
true
else:
false
var deck = newDeck()
var players = newPlayerArr()
shuffle deck
for _ in 1..nDeals:
var cards: seq[Card]
if deck.deal(cards):
for p in zip(players, cards):
p[0].hand.add p[1]
I first was thinking of doing a "minimalist" thing since you can take five random cards from a decreasing set (move last card to picked card, cards-1).
Put mine over Took me a while, and I would still like to clean up the players so I don't need the global structure accessed from main.
Or just use array.pop()
> I first was thinking of doing a "minimalist" thing since you can take five random cards from a decreasing set (move last card to picked card, cards-1).
Imagine being creepy enough to take a pic like that.
fuck, pasted the wrong code, this is a good bit cleaner
import random, sequtils
const
playerCount = 5
nDeals = 5
type
Suit {.pure.} = enum
Heart, Diamond, Club, Spade
Card = object
suit: Suit
value: range[1..13]
Player = ref object
hand: seq[Card]
proc newDeck: seq[Card] =
result = @[]
for s in Suit.low..Suit.high:
for v in 1..13:
result.add Card(suit: s, value: v)
proc newPlayerArr: array[1..playerCount, Player] =
for i in 1..playerCount:
result[i] = Player(hand: newSeq[Card]())
iterator deal(deck: var seq[Card]): (int, Card) =
if deck.len >= playerCount:
for i in 1..playerCount:
let x = deck[deck.high]
deck.delete(deck.high)
yield (i, x)
var
deck = newDeck()
players = newPlayerArr()
shuffle deck
for _ in 1..nDeals:
for i, c in deal(deck):
players[i].hand.add c
for p in players:
echo p.hand
Stupid fucking normie Apple product using cunt whore I wanna watch her choke to death
import random
var suits = ["Heart", "Diamond", "Club", "Spade"]
var numbers = ["Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"]
var deck
foreach suit in suits:
foreach number in numbers:
deck.append(number + " of " + suit)
end
end
random.shuffle(deck)
var table
var a = deck
var players = ["playerA", "playerB", "playerC", "playerD", "playerE"]
var pcards
foreach i in range(1,6):
foreach player in players
z = random.choice(a)
a.remove(z)
pcards.append([player, z])
end
end
fuck classes. pure linear coding will do.
>tfw I will never get to filter her digestive gasses through those pants and in to my lungs
whut did you just say? I'm using C89.
>what did she mean by this face?
tfw no tinder matches for 12 seconds
>shuffle
are there requirements for shuffling to result in realistic shuffling result?
Use the Fisher-Yates algorithm.
>what did she mean by this face?
some fucking creep taking pictures of her on the train and posting them on the internet even after she noticed him
>are you really going to fuck me on this bus?
Way to go above your requirements. Failed. OP said 5 cards to 5 players, not a bunch of variables taking up space for names and an undetermined amount of players. You used too much space trying to be le modular. A simple task was given and you couldn't do it. Reevaluate yourself
In c++ with funlib this is just
const auto players =eval( Integers(0,52) | Shuffle() | Take(25) | Map(toCards) | Fold(toFiveLists) )
Tocards and toFiveLists are trivial and left as an exercise to the reader
Could have also done UnifomDist(0,52) | Unique()
eyebrows
>using emojis in code
If you dress like a whore dont be suprised when old creepy men treat you like one.
I have a better coding challenge.
Make a Neural network which makes her nudes.
What should she wear then?
Shouldn't change a thing. Whores should keep dressing like whores, so that decent men can identify and avoid them easier.
Gold
Is this lang efficient though? Or is it just using a small amount of characters for functions?
I imagine the small amount of characters adds up to far less bits with larger programs.
import random
deck = [card for elem in [[f'{x}{z}' for x in list(range(2,11)) + ['J','Q','K','A']] for z in ['C','D','H','S']] for card in elem]
fp = [deck.pop(random.randint(1,len(deck))) for x in range(5)]
sc = [deck.pop(random.randint(1,len(deck))) for x in range(5)]
case class Card(private val repr: Int){
val suit = repr match {
case a if a/13 == 0 => "Hearts"
case a if a/13 == 1 => "Clover"
case a if a/13 == 2 => "Clubs"
case a => "Spades"
}
val value = repr % 13 match {
case a if a == 1 => "Ace"
case a if a == 13 => "King"
case a if a == 12 => "Queen"
case a if a == 11 => "Knight"
case a => s"$a"
}
}
(0 until 13*4).shuffle.take(5*5).grouped(5).map(Card.apply)
not testetd lol, prorbably wont even compile
implicit class RangeOps[A](xs: Seq[A]){
def shuffle: Seq[A] = util.Random.shuffle(xs)
}
case class Card(private val repr: Int){
val suit = repr match {
case a if a/13 == 0 => "Hearts"
case a if a/13 == 1 => "Clover"
case a if a/13 == 2 => "Clubs"
case a => "Spades"
}
val value = repr % 13 match {
case a if a == 1 => "Ace"
case a if a == 13 => "King"
case a if a == 12 => "Queen"
case a if a == 11 => "Knight"
case a => s"$a"
}
override def toString: String = value +" of "+ suit
}
val cards = (0 until 13*4).shuffle.take(5*5).map(Card).grouped(5)
println(cards.mkString("\n"))
Actual compiling version
Based mudslime
I'd say its bad cause he cant decide whenever make it fully abstract and modular or hardcoded for one specific thng.
So he tries to do both and ends up with half-assed half-hardcoded half-modular bullshit
Either way it's poor development practice and would surely not land a job. Didn't meet the requirements and wasn't consistent design ideology. It's as if he attempted to lay out the program by deciding to have initPlayers and initDeck, threw in a shuffle and deal, when he could have combined initDeck and shuffle into one method or did it linearly in a main(). And could have dealt right to 5 players.
Oh well, I guess overcompensation is a regular thing for programmers tho
This is fan fucking tastic
Decided to do it in C++ cause I need to train this language a bit. God all the shit that I had forgotten about this language's syntax.
All in all I'm pretty satisfied with what I've done, especially my shuffle.
A burka
Using python, unicode playing card symbols ( en.wikipedia.org
import random
def make_deck():
def suit_from_ace(ace):
return [chr(ord(ace) + i) for i in range(0, 14)]
return [card for ace in '' for card in suit_from_ace(ace)]
def pop_n_cards(deck, n):
assert n
Jow Forums ate my output.
import random
def carddrawing(x):
cards = []
cardsdrawn = []
for i in ["C", "D", "H", "S"]:
for n in range(1, 11):
cards.append(i + str(n))
for b in ["J", "Q", "K", "A"]:
cards.append(i + b)
for n in range(0, x):
cardget = random.randrange(0, len(cards))
cardsdrawn.append(cards[cardget])
cards.remove(cards[cardget])
print(cards)
print(cardsdrawn)
carddrawing(3)
stop posting pictures of my gf
implementing fisher-yates over IO MArray
{-# LANGUAGE FlexibleContexts #-}
module Cards where
import System.Random
import Data.Array.IO
takeGroup _ [] = []
takeGroup n xs = (take n xs) : takeGroup n (drop n xs)
loop a 1 = return a
loop a i = do
j
import random
def carddrawing(x):
cards = []
cardsdrawn = []
for i in ["C", "D", "H", "S"]:
for n in range(1, 11):
cards.append(i + str(n))
for b in ["J", "Q", "K", "A"]:
cards.append(i + b)
for n in range(0, x):
cardget = random.randrange(0, len(cards))
cardsdrawn.append(cards[cardget])
cards.remove(cards[cardget])
print(cards)
print(cardsdrawn)
carddrawing(3)
She needs to breed
Second try posting and I included the one starting at 1 instead of 2... It's a hard life being a brainlet
crap, forgot to use getElems instead