Example #1
0
func Euler041() int {
	//process 7 digit pandigitals
	p7d := make([]int, 0, 5040) //7!
	for v := range utils.Perm(utils.Numerals[1:8]) {
		n, _ := strconv.Atoi(v)
		p7d = append(p7d, n)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(p7d)))

	for i := 0; i < 5040; i++ {
		if utils.IsPrime(p7d[i]) {
			return p7d[i]
		}
	}

	//process 4 digit pandigitals
	p4d := make([]int, 0, 24) //4!
	for v := range utils.Perm(utils.Numerals[1:5]) {
		n, _ := strconv.Atoi(v)
		p4d = append(p4d, n)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(p4d)))

	for i := 0; i < 5040; i++ {
		if utils.IsPrime(p4d[i]) {
			return p4d[i]
		}
	}

	return -1
}
Example #2
0
func main() {

	studyGroup := people{"Zeno", "Ian", "John", "Al", "Jenny"}

	fmt.Println("1: = sorting slice of strings of type people by name:")
	fmt.Println("\to:", studyGroup)
	sort.Strings(studyGroup)
	fmt.Println("\t\t [Strings method]:", studyGroup)
	sort.Sort(sort.StringSlice(studyGroup))
	fmt.Println("\t\t [StringSlice interface conversion]", studyGroup)
	sort.Sort(sort.Reverse(sort.StringSlice(studyGroup)))
	fmt.Println("\t\t [Reverse]", studyGroup)

	fmt.Println("2: = by literal slice of strings")
	s := []string{"Zeno", "John", "Al", "Jenny", "Ben"}
	fmt.Println("\to:", s)
	sort.Strings(s)
	fmt.Println("\t\t [Strings method]:", s)
	sort.Sort(sort.StringSlice(s))
	fmt.Println("\t\t [StringSlice interface conversion]", s)
	sort.Sort(sort.Reverse(sort.StringSlice(s)))
	fmt.Println("\t\t [Reverse]", s)

	fmt.Println("3: = slice of ints")
	n := []int{7, 4, 8, 2, 9, 19, 12, 32, 3}
	fmt.Println("\to:", n)
	sort.Ints(n)
	fmt.Println("\t\t [Ints method]", n)
	sort.Sort(sort.IntSlice(n))
	fmt.Println("\t\t [IntSlice interface conversion]", n)
	sort.Sort(sort.Reverse(sort.IntSlice(n)))
	fmt.Println("\t\t [Reverse]", n)

}
Example #3
0
func reduceSlices(numerator, denominator []int) ([]int, []int) {
	sortedNum := sort.IntSlice(numerator)
	sortedNum.Sort()
	sortedDenom := sort.IntSlice(denominator)
	sortedDenom.Sort()
	j := 0
	resNum := make([]int, 0)
	resDenom := make([]int, 0)
	for i := 0; i < len(sortedNum); {
		if j > len(sortedDenom)-1 {
			resNum = concatInt(resNum, sortedNum[i:])
			break
		}
		if sortedNum[i] == sortedDenom[j] {
			j++
			i++
			continue
		}
		if sortedNum[i] > sortedDenom[j] {
			resDenom = append(resDenom, sortedDenom[j])
			j++
			continue
		}
		resNum = append(resNum, sortedNum[i])
		i++
	}
	if j < len(sortedDenom) {
		resDenom = concatInt(resDenom, sortedDenom[j:])
	}
	return resNum, resDenom
}
Example #4
0
func TestDedup(t *testing.T) {
	a := []int{}
	n := Dedupe(sort.IntSlice(a))
	if g, e := n, 0; g != e {
		t.Fatal(g, e)
	}

	if g, e := len(a), 0; g != e {
		t.Fatal(g, e)
	}

	for c := 1; c <= 7; c++ {
		in := make([]int, c)
		lim := int(mathutil.ModPowUint32(uint32(c), uint32(c), math.MaxUint32))
		for n := 0; n < lim; n++ {
			m := n
			for i := range in {
				in[i] = m % c
				m /= c
			}
			in0 := append([]int(nil), in...)
			out0 := dedupe(in)
			n := Dedupe(sort.IntSlice(in))
			if g, e := n, len(out0); g != e {
				t.Fatalf("n %d, exp %d, in0 %v, in %v, out0 %v", g, e, in0, in, out0)
			}

			for i, v := range out0 {
				if g, e := in[i], v; g != e {
					t.Fatalf("n %d, in0 %v, in %v, out0 %v", n, in0, in, out0)
				}
			}
		}
	}
}
Example #5
0
func Test_set(t *testing.T) {

	a := []int{1, 2, 3, 4}
	aSet := NewIntSet()
	aSet.Add(a...)
	cSet := aSet.Clone()

	if !aSet.Equals(cSet) {
		t.Error("set equality does not work properly.")
	}

	b := []int{3, 4, 5, 6}
	bSet := NewIntSet()
	bSet.Add(b...)

	if !aSet.Contains(3) || aSet.Contains(10) {
		t.Error("set containment does not work properly.")
	}

	aList := sort.IntSlice(aSet.ToList())
	aList.Sort()
	for i, l := range a {
		if aList[i] != l {
			t.Error("list representation of aSet does not match a")
		}
	}

	bList := sort.IntSlice(bSet.ToList())
	bList.Sort()
	for i, l := range bList {
		if b[i] != l {
			t.Error("list representation of bSet does not match b")
		}
	}

	aSet.Union(bSet)
	aList = sort.IntSlice(aSet.ToList())
	aList.Sort()
	for i, l := range []int{1, 2, 3, 4, 5, 6} {
		if aList[i] != l {
			t.Error("union operation on aSet and bSet failed")
		}
	}

	aSet.Complement(bSet)
	aList = sort.IntSlice(aSet.ToList())
	aList.Sort()
	for i, l := range []int{1, 2} {
		if aList[i] != l {
			t.Error("complement operation on aSet and bSet failed")
		}
	}

	aSet.Intersect(bSet)
	aList = sort.IntSlice(aSet.ToList())
	aList.Sort()
	if len(aList) != 0 {
		t.Error("intersect operation on aSet and bSet failed")
	}
}
Example #6
0
func main() {
	// sort people as type
	studyGroup := people{"Zeno", "John", "Al", "Jenny"}

	fmt.Println(studyGroup)
	sort.Sort(studyGroup)
	fmt.Println(studyGroup)
	sort.Sort(sort.Reverse(studyGroup))
	fmt.Println(studyGroup)

	// sort s as string slice
	s := []string{"Zeno", "John", "Al", "Jenny"}
	fmt.Println(s)
	sort.StringSlice(s).Sort()
	fmt.Println(s)
	sort.Sort(sort.Reverse(sort.StringSlice(s)))
	fmt.Println(s)

	// sort n as int slice
	n := []int{7, 4, 8, 2, 9, 19, 12, 32, 3}
	fmt.Println(n)
	sort.IntSlice(n).Sort()
	fmt.Println(n)
	sort.Sort(sort.Reverse(sort.IntSlice(n)))
	fmt.Println(n)
}
Example #7
0
func testSortFn(t *testing.T, fn sortFn, fnName string) {
	for _, test := range []sort.Interface{
		sort.IntSlice([]int{660, 14, 796, 336, 223, 594, 419, 574, 372, 103, 991, 718, 436, 351, 844, 277, 668, 250, 330, 86}),
		sort.Float64Slice([]float64{213.237, 458.642, 978.311, 547.351, 57.8992, 245.518, 445.638, 251.79, 960.202, 100.069, 483.136, 407.858, 496.913, 562.943, 557.959, 219.648, 164.599, 843.304, 671.732, 222.676}),
		sort.StringSlice([]string{"assaults", "brackish", "monarchism", "ascribe", "mechanize", "andiron", "overpricing", "jading", "hauliers", "snug", "zodiac", "credit", "tremendous", "palavered", "hibiscuses", "amplest", "interrogated", "geologic", "unorthodoxy", "propagated"}),
	} {
		// Make a copy to avoid modification of the original slice.
		var data sort.Interface
		switch v := test.(type) {
		case sort.IntSlice:
			data = append(sort.IntSlice(nil), v...)
		case sort.Float64Slice:
			data = append(sort.Float64Slice(nil), v...)
		case sort.StringSlice:
			data = append(sort.StringSlice(nil), v...)
		default:
			t.Errorf("missing case: cannot copy %T", v)
			continue
		}
		fn(data)
		if !sort.IsSorted(data) {
			t.Errorf("%s(%v)", fnName, test)
			t.Errorf(" got %v", data)
			sort.Sort(data)
			t.Errorf("want %v", data)
		}
	}
}
Example #8
0
File: utils.go Project: sb10/vrpipe
// SortMapKeysByIntValue sorts the keys of a map[string]int by its values,
// reversed if you supply true as the second arg.
func SortMapKeysByIntValue(imap map[string]int, reverse bool) (sortedKeys []string) {
	// from http://stackoverflow.com/a/18695428/675083 *** should also try the
	// idiomatic way to see if that's better in any way
	valToKeys := map[int][]string{}
	for key, val := range imap {
		valToKeys[val] = append(valToKeys[val], key)
	}
	var vals []int
	for val := range valToKeys {
		vals = append(vals, val)
	}

	if reverse {
		sort.Sort(sort.Reverse(sort.IntSlice(vals)))
	} else {
		sort.Sort(sort.IntSlice(vals))
	}

	for _, val := range vals {
		for _, key := range valToKeys[val] {
			sortedKeys = append(sortedKeys, key)
		}
	}

	return
}
Example #9
0
File: utils.go Project: sb10/vrpipe
// SortMapKeysByMapIntValue sorts the keys of a map[string]map[string]int by
// a the values found at a given sub value, reversed if you supply true as the
// second arg.
func SortMapKeysByMapIntValue(imap map[string]map[string]int, criterion string, reverse bool) (sortedKeys []string) {
	criterionValueToKeys := make(map[int][]string)
	for key, submap := range imap {
		val := submap[criterion]
		criterionValueToKeys[val] = append(criterionValueToKeys[val], key)
	}
	var criterionValues []int
	for val := range criterionValueToKeys {
		criterionValues = append(criterionValues, val)
	}

	if reverse {
		sort.Sort(sort.Reverse(sort.IntSlice(criterionValues)))
	} else {
		sort.Sort(sort.IntSlice(criterionValues))
	}

	for _, val := range criterionValues {
		for _, key := range criterionValueToKeys[val] {
			sortedKeys = append(sortedKeys, key)
		}
	}

	return
}
Example #10
0
func main() {
	filename := "A-small-practice.in"
	lines, err := readLines(filename)
	if err != nil {
		log.Fatalf("readLines: %s", err)
	}

	testCases, _ := strconv.Atoi(lines[0])
	var s []string

	for i := 1; i < testCases*3; i += 3 {
		var v1 []string = strings.Split(lines[i+1], " ")
		var v2 []string = strings.Split(lines[i+2], " ")
		var v1i, v2i []int
		ans := 0
		tmpLen, _ := strconv.Atoi(lines[i])
		for j := 0; j < tmpLen; j++ {
			tmp, _ := strconv.Atoi(v1[j])
			v1i = append(v1i, tmp)
			tmp, _ = strconv.Atoi(v2[j])
			v2i = append(v2i, tmp)
		}
		sort.Sort(sort.IntSlice(v1i))
		sort.Sort(sort.Reverse(sort.IntSlice(v2i)))

		for j := 0; j < tmpLen; j++ {
			ans += v1i[j] * v2i[j]
		}
		s = append(s, "Case #"+strconv.Itoa((i/3)+1)+": "+strconv.Itoa(ans))
	}
	if err := writeLines(s, "A-small-practice.out"); err != nil {
		log.Fatalf("Error!", err)
	}
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
	ch1, ch2, done := make(chan int), make(chan int), make(chan int)
	r1, r2 := make([]int, 0), make([]int, 0)

	go func() {
		Walk(t1, ch1)
		done <- 1
	}()
	go func() {
		Walk(t2, ch2)
		done <- 1
	}()
	for n := 2; n > 0; {
		select {
		// these two cases are almost identical, I wish I knew how to
		// write a case that reads when both channels are ready
		case v1 := <-ch1:
			// this read could block indefinitely if t1 and t2
			// have different sizes
			v2 := <-ch2
			if v1 != v2 {
				// push these values into a slice for comparison later
				r1 = append(r1, v1)
				r2 = append(r2, v2)
			}
		case v2 := <-ch2:
			// this read could block indefinitely if t1 and t2
			// have different sizes
			v1 := <-ch1
			if v1 != v2 {
				// push these values into a slice for comparison later
				r1 = append(r1, v1)
				r2 = append(r2, v2)
			}
		case <-done:
			n--
		}
	}

	// if there are any remaining values, make sure they are all the same
	if len(r1) != 0 || len(r2) != 0 {
		if len(r1) != len(r2) {
			// this will never get hit as it would block indefinitely in the
			// select above
			return false
		}
		// sort slices to make them easy to compare
		is1 := sort.IntSlice(r1)
		is2 := sort.IntSlice(r2)
		sort.Sort(is1)
		sort.Sort(is2)
		for i, x := range is1 {
			if x != is2[i] {
				return false
			}
		}
	}
	return true
}
Example #12
0
func benchRandom(b *testing.B, fn sortFn, size int) {
	b.StopTimer()
	ints := sort.IntSlice(rand.New(rand.NewSource(int64(size))).Perm(size))
	for i := 0; i < b.N; i++ {
		data := append(sort.IntSlice(nil), ints...)
		b.StartTimer()
		fn(data)
		b.StopTimer()
	}
}
Example #13
0
func main() {
	{
		values := []int{3, 1, 4, 1}
		fmt.Println(IsPalindrome(sort.IntSlice(values))) // "false"
	}
	{
		values := []int{3, 1, 4, 1, 3}
		fmt.Println(IsPalindrome(sort.IntSlice(values))) // "true"
	}
}
Example #14
0
func products(delta int) []int {
	r := []int{}
	a := 999
	b := 999 - delta
	for a >= b {
		r = append(r, a*b)
		a -= 1
		b += 1
	}

	sort.Sort(sort.Reverse(sort.IntSlice(r)))
	return sort.IntSlice(r)
}
Example #15
0
func ExampleIsUniqued() {
	fmt.Println(unique.IsUniqued(sort.IntSlice([]int{1, 2, 3})))
	fmt.Println(unique.IsUniqued(sort.IntSlice([]int{1, 2, 2, 3})))
	// false because it isn't sorted as well.
	fmt.Println(unique.IsUniqued(sort.IntSlice([]int{3, 2, 1})))
	fmt.Println(unique.IsUniqued(sort.IntSlice([]int{})))

	// Output:
	// true
	// false
	// false
	// true
}
Example #16
0
// Algorithm: Multiply the largest number by the smallest number.
func (t *Solver) MinInnerProduct() int {
	a1 := sort.IntSlice(t.arr1)
	a1.Sort()
	a2 := sort.IntSlice(t.arr2)
	a2.Sort()
	base.ReverseInts(a2)

	out := 0
	for i := 0; i < len(a1); i++ {
		out += a1[i] * a2[i]
	}
	return out
}
func sortHand(unsorted Hand) Hand {
	switch Trump {
	case 'C':
		return sort.IntSlice(unsorted.ClubsRank)
	case 'H':
		return sort.IntSlice(unsorted.HeartsRank)
	case 'S':
		return sort.IntSlice(unsorted.SpadesRank)
	case 'D':
	default:
		return sort.IntSlice(unsorted.DiamondsRank)
	}
}
func sameContents(a, b []int) bool {
	if len(a) != len(b) {
		panic("y u pass different length slices")
	}
	sort.IntSlice(a).Sort()
	sort.IntSlice(b).Sort()
	for i := range a {
		if a[i] != b[i] {
			return false
		}
	}
	return true
}
Example #19
0
func benchNearlySorted(b *testing.B, fn sortFn, size int) {
	b.StopTimer()
	ints := sort.IntSlice(rand.New(rand.NewSource(int64(size))).Perm(size))
	sort.Sort(ints)
	for i := 2; i < len(ints); i += 4 {
		ints[i], ints[i-2] = ints[i-2], ints[i]
	}
	for i := 0; i < b.N; i++ {
		data := append(sort.IntSlice(nil), ints...)
		b.StartTimer()
		fn(data)
		b.StopTimer()
	}
}
Example #20
0
func main() {

	//var n sort.IntSlice

	n := []int{7, 4, 8, 2, -9, 12, -23, 32, 3}

	sort.Sort(sort.Reverse(sort.IntSlice(n)))

	//sort.Sort(sort.IntSlice(n))
	fmt.Printf("\n %T \n", sort.Reverse(sort.IntSlice(n)))
	fmt.Println(n)

	//fmt.Println(n)

}
Example #21
0
// newHand constructs a new Hand type from the given cards.
// cards is of the form e.g. [AC 8D 8H 3C 2S]
func newHand(cards []string) Hand {
	trans := map[string]int{"A": 14, "K": 13, "Q": 12, "J": 11, "T": 10}

	var ranks []int                  // The ranks field.
	suits := make(map[string]bool)   // The suits field.
	rankToCount := make(map[int]int) // Used to create other fields.
	for _, card := range cards {
		s := string(card[1])
		suits[s] = true
		r, ok := trans[string(card[0])]
		if !ok {
			r, _ = strconv.Atoi(string(card[0]))
		}
		ranks = append(ranks, r)
		rankToCount[r]++
	}
	sort.Sort(sort.Reverse(sort.IntSlice(ranks)))

	// An ace should be played 'low' i.e. with rank 1 if it makes a straight.
	if reflect.DeepEqual(ranks, []int{14, 5, 4, 3, 2}) {
		ranks = []int{5, 4, 3, 2, 1}
	}

	var pattern []int                   // The pattern field.
	countToRanks := make(map[int][]int) // Used to create the groups field.
	for k, v := range rankToCount {
		pattern = append(pattern, v)
		countToRanks[v] = append(countToRanks[v], k)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(pattern)))

	var groups [][]int         // The groups field.
	seen := make(map[int]bool) // Used to ensure no duplicates.
	for _, count := range pattern {
		// For every count in the pattern append to groups a [count rank] pair.
		// groups is ordered by highest count first, then highest rank first.
		if !seen[count] {
			rs := countToRanks[count]
			sort.Sort(sort.Reverse(sort.IntSlice(rs)))
			for _, r := range rs {
				groups = append(groups, []int{count, r})
			}
		}
		seen[count] = true
	}

	return Hand{ranks, suits, groups, pattern}
}
Example #22
0
// Yay, sorting things is so easy in go
func keysByIntValDesc(m map[string]int) []string {
	// Invert the map
	inv := map[int][]string{}
	for k, v := range m {
		inv[v] = append(inv[v], k)
	}

	// List the unique vals
	vals := []int{}
	for k, _ := range inv {
		vals = append(vals, k)
	}

	// Sort the vals
	sort.Sort(sort.Reverse(sort.IntSlice(vals)))

	// Now list the keys corresponding to each val
	keys := []string{}
	for _, val := range vals {
		for _, key := range inv[val] {
			keys = append(keys, key)
		}
	}

	return keys
}
Example #23
0
func Test_divide(t *testing.T) {
	//Test if dividing the message works
	var keys []int
	for key, _ := range IPs {
		keys = append(keys, key)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(keys)))

	fixtures := map[int]map[int]int{
		11:  map[int]int{25: 0, 10: 1, 5: 0, 1: 1},
		100: map[int]int{25: 4, 10: 0, 5: 0, 1: 0},
		107: map[int]int{25: 4, 10: 0, 5: 1, 1: 2},
		4:   map[int]int{25: 0, 10: 0, 5: 0, 1: 4},
	}
	for input, expected := range fixtures {
		result := divide(input, keys)
		failed := false
		for k, v := range expected {
			if result[k] != v {
				failed = true
			}
		}
		if failed {
			t.Error(fmt.Sprintf("Dividing %d expected %v, got %v", input, expected, result))
		}
	}
}
Example #24
0
func (s *SudokuSolver) Solve(sudoku [][]int) *Solution {
	partial := s.gridToCover(sudoku)
	// Iterate through the digits from biggest to smallest.
	keys := make([]int, 0, len(partial))
	for key, _ := range partial {
		keys = append(keys, key)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(keys)))
	// log.Println("Initial config is", partial)
	O := new(Solution)
	k := 0
	m := s.matrix
	for _, digit := range keys {
		for _, c := range partial[digit] {
			// Find the column for existence constraint, so that all the digits are available inside.
			n := m.Col(c)
			n.Cover()
			// Move down by <digit> nodes to find the row to include in the solution.
			for j := 0; j < digit; j++ {
				n = n.Down
			}
			O.Set(k, n)
			for o := n.Right; o != n; o = o.Right {
				o.Col.Cover()
			}
			k++
		}
	}
	// fmt.Printf("Initial solution is\n%v", O)
	s.matrix.Search(O, k, s)
	return O
}
Example #25
0
File: pot.go Project: notnil/joker
// resultsFromWinners forms results for winners of the pot
func (p *Pot) resultsFromWinners(winners hands, chips, button int, f func(n int) Share) map[int][]*Result {
	results := map[int][]*Result{}
	winningSeats := []int{}
	for seat, hand := range winners {
		winningSeats = append(winningSeats, int(seat))
		results[seat] = []*Result{&Result{
			Hand:  hand,
			Chips: chips / len(winners),
			Share: f(len(winners)),
		}}
	}
	sort.IntSlice(winningSeats).Sort()

	remainder := chips % len(winners)
	for i := 0; i < remainder; i++ {
		seatToCheck := (button + i) % 10
		for _, seat := range winningSeats {
			if seat == seatToCheck {
				results[seat][0].Chips++
				break
			}
		}
	}
	return results
}
Example #26
0
func encodeSettingsV3(s Settings) []byte {
	if len(s) == 0 {
		return []byte{}
	}

	ids := make([]int, 0, len(s))
	for id := range s {
		ids = append(ids, int(id))
	}

	sort.Sort(sort.IntSlice(ids))

	out := make([]byte, 8*len(s))

	offset := 0
	for _, id := range ids {
		setting := s[uint32(id)]
		out[offset] = byte(setting.Flags)
		out[offset+1] = byte(setting.ID >> 16)
		out[offset+2] = byte(setting.ID >> 8)
		out[offset+3] = byte(setting.ID)
		out[offset+4] = byte(setting.Value >> 24)
		out[offset+5] = byte(setting.Value >> 16)
		out[offset+6] = byte(setting.Value >> 8)
		out[offset+7] = byte(setting.Value)
		offset += 8
	}

	return out
}
Example #27
0
func (w *PkgWalker) LookupImport(pkg *types.Package, pkgInfo *types.Info, cursor *FileCursor, is *ast.ImportSpec) {
	fpath, err := strconv.Unquote(is.Path.Value)
	if err != nil {
		return
	}
	fbase := fpath
	pos := strings.LastIndexAny(fpath, "./-\\")
	if pos != -1 {
		fbase = fpath[pos+1:]
	}
	fid := fpath + "." + fbase
	//kind := ObjPkgName
	//fmt.Println(kind, true)

	if typeFindDef {
		fmt.Println(w.fset.Position(is.Pos()))
	}
	if typeFindInfo {
		fmt.Println("package", fpath)
	}
	if !typeFindUse {
		return
	}
	var usages []int
	for id, obj := range pkgInfo.Uses {
		if obj != nil && obj.Id() == fid { //!= nil && cursorObj.Pos() == obj.Pos() {
			usages = append(usages, int(id.Pos()))
		}
	}
	(sort.IntSlice(usages)).Sort()
	for _, pos := range usages {
		fmt.Println(w.fset.Position(token.Pos(pos)))
	}
}
Example #28
0
func main() {
	f, err := os.OpenFile("input_24.txt", os.O_RDONLY, 0666)
	//f, err := os.OpenFile("easy_24", os.O_RDONLY, 0666)
	if err != nil {
		return
	}
	defer f.Close()
	r := bufio.NewReader(f)

	for {
		line, err := r.ReadString('\n')
		if err != nil {
			break
		}
		line = strings.TrimRight(line, "\n\r")
		p, _ := strconv.Atoi(line)
		PACKS = append(PACKS, p)
		GROUP_SUM += p
	}
	GROUP_SUM /= GROUPS

	fmt.Println("Size:", len(PACKS), "group sum:", GROUP_SUM)
	sort.Sort(sort.Reverse(sort.IntSlice(PACKS)))
	fmt.Println("Packs:", PACKS)

	first(0, 0, 0, 1)
	fmt.Println("BEST:", BEST)
}
Example #29
0
/*rankHand scores a poker hand.
First by determining the type of hand,
Then by sorting the card ranks into their order of comparison.*/
func rankHand(ranks [5]int, suits string) [6]int {
	cardGroups := groupCards(&ranks)

	// Change ranks if ace is played low
	if ranks == [5]int{14, 5, 4, 3, 2} {
		ranks = [5]int{5, 4, 3, 2, 1}
	}
	isFlush, isStraight := isFlush(suits), isStraight(ranks)

	var handRank [6]int
	switch {
	case isFlush && isStraight:
		handRank[0] = straightFlush
	case cardGroups == "41":
		handRank[0] = fourOfAKind
	case cardGroups == "32":
		handRank[0] = fullHouse
	case isFlush:
		// Reorder so that flush can have multiple cards of the same value
		sort.Sort(sort.Reverse(sort.IntSlice(ranks[:])))
		handRank[0] = flush
	case isStraight:
		handRank[0] = straight
	case cardGroups == "311":
		handRank[0] = threeOfAKind
	case cardGroups == "221":
		handRank[0] = twoPair
	case cardGroups == "2111":
		handRank[0] = onePair
	default:
		handRank[0] = highCard
	}
	copy(handRank[1:6], ranks[:])
	return handRank
}
func BenchmarkQuickSort(b *testing.B) {
	for i := 0; i < b.N; i++ {
		bigData := geneBigData()
		QuickSort(sort.IntSlice(bigData), nil)
		checkSortedData(bigData)
	}
}