Skip to content

Instantly share code, notes, and snippets.

@techslides
Last active August 29, 2015 14:05
Show Gist options
  • Save techslides/359cad61ec00010a2918 to your computer and use it in GitHub Desktop.
Save techslides/359cad61ec00010a2918 to your computer and use it in GitHub Desktop.
Go Lang Route to Split and Shuffle Array of Objects
m.Get("/cards/:players", allowCORSHandler, func(args martini.Params, r render.Render) {
Shuffle(cards)
//use Atoi as ParseInt always does int64
p, _ := strconv.Atoi(args["players"])
if(p==0 || p>52){
//not valid number
r.JSON(200, cards)
} else {
var total = len(cards)
var start = 0
var split = total/p
//for sorting by suit and number
suit := func(c1, c2 *Card) bool {
return c1.Suit < c2.Suit
}
numbers := func(c1, c2 *Card) bool {
return c1.Number < c2.Number
}
//make a multidiemnsional array in Go (http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime#Go) with as many items in array as players so we can loop and fill below
var a = make([][]Card,p)
for i := range a {
var psplit = cards[start:start+split];
// Sort by Number and Suit
OrderedBy(suit, numbers).Sort(psplit)
a[i]=psplit
start=start+split
}
//kitty
var kittycards = cards[start:total]
r.JSON(200, map[string]interface{}{"players": a, "kitty":kittycards})
}
@techslides
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment