Last active
August 29, 2015 14:05
-
-
Save techslides/359cad61ec00010a2918 to your computer and use it in GitHub Desktop.
Go Lang Route to Split and Shuffle Array of Objects
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
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}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Look at the full code here: https://github.com/techslides/gae-go-cards-api/blob/master/hello.go