Created
February 6, 2016 02:37
-
-
Save mickelsonm/129663f9f985b733f6c3 to your computer and use it in GitHub Desktop.
Go Slice Distribution Example
This file contains hidden or 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
package main | |
import "fmt" | |
// Divides `slice` into `n` subslices such that the elements are distributed | |
// as evenly as possible. In other words, if there are 10 elements in `slice`, | |
// and `n` is 3, there will be one subslice with 4 elements and the others will | |
// have only 3. | |
func subslice(s []interface{}, n int)(ret [][]interface{}){ | |
for ; n > 0; n-- { | |
s, ret = s[len(s)/n:], append(ret, s[:len(s)/n]) | |
} | |
return ret | |
} | |
func main() { | |
fmt.Println(subslice([]interface{}{"a","b","c",1,2,3}, 4)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment