func solver(in *ProblemReader.ProblemReader) string { n := in.Num() v1 := in.NNums(n) v2 := in.NNums(n) sort.SortInts(v1) sort.SortInts(v2) var sum int64 = 0 for j := 0; j < n; j++ { sum += int64(v1[j]) * int64(v2[n-j-1]) } return fmt.Sprint(sum) }
func testAfterQueuing(t *testing.T) os.Error { const ( Delta = 100 * 1e6 ) // make the result channel buffered because we don't want // to depend on channel queueing semantics that might // possibly change in the future. result := make(chan afterResult, len(slots)) t0 := Nanoseconds() for _, slot := range slots { go await(slot, result, After(int64(slot)*Delta)) } sort.SortInts(slots) for _, slot := range slots { r := <-result if r.slot != slot { return fmt.Errorf("after queue got slot %d, expected %d", r.slot, slot) } ns := r.t - t0 target := int64(slot * Delta) slop := int64(Delta) / 4 if ns < target-slop || ns > target+slop { return fmt.Errorf("after queue slot %d arrived at %g, expected [%g,%g]", slot, float64(ns), float64(target-slop), float64(target+slop)) } } return nil }
func TestMemberSimple(t *testing.T) { st := store.New() defer close(st.Ops) fp := &test.FakeProposer{Store: st} c := make(chan string) go Clean(c, fp.Store, fp) fp.Propose([]byte(store.MustEncodeSet("/ctl/node/a/x", "a", store.Missing))) fp.Propose([]byte(store.MustEncodeSet("/ctl/node/a/y", "b", store.Missing))) fp.Propose([]byte(store.MustEncodeSet("/ctl/node/a/addr", "1.2.3.4", store.Missing))) fp.Propose([]byte(store.MustEncodeSet("/ctl/cal/0", "a", store.Missing))) calCh := fp.Watch(store.MustCompileGlob("/ctl/cal/0")) nodeCh := fp.Watch(store.MustCompileGlob("/ctl/node/a/?")) // indicate that this peer is inactive go func() { c <- "1.2.3.4" }() ev := <-calCh assert.T(t, ev.IsSet()) assert.Equal(t, "", ev.Body) cs := []int{} ev = <-nodeCh assert.T(t, ev.IsDel()) cs = append(cs, int(ev.Path[len(ev.Path)-1])) ev = <-nodeCh assert.T(t, ev.IsDel()) cs = append(cs, int(ev.Path[len(ev.Path)-1])) sort.SortInts(cs) assert.Equal(t, []int{'x', 'y'}, cs) }
func generateEquivalentProductsRecursive(product []int, resultMap map[string][]int) { productString := fmt.Sprint(product) if _, ok := resultMap[productString]; ok == true { return } resultMap[productString] = product done := make(map[int]bool) for i := 0; i < len(product); i += 1 { for j := i + 1; j < len(product); j += 1 { p := product[i] * product[j] done[p] = true productTmp := vector.IntVector(product) productCopy := productTmp.Copy() productCopy.Delete(j) productCopy.Set(i, p) sort.SortInts(productCopy) generateEquivalentProductsRecursive(productCopy, resultMap) } } }
func main() { s := make([]int, 1000000) for i, _ := range s { s[i] = 1000000 - i } println(s[999999]) sort.SortInts(s) println(s[999999]) }
func TestHeap(t *testing.T) { heap := NewSize(1) // make it short to test resize nums := randomInts(1000) elmts := make([]Heapable, len(nums)) for i := 0; i < len(nums); i++ { elmts[i] = &heaper{nums[i]} } heap.AddSlice(elmts) if heap.Len() != len(nums) { t.Fatalf("heap.Len() != %d\n", len(nums)) } sort.SortInts(nums) for i := 0; i < len(nums); i++ { if heap.Remove().Priority() != nums[i] { t.Fatalf("binheap: Priority() != %d\n", nums[i]) } } if !heap.Empty() { t.Fatalf("heap not empty\n") } nums = randomInts(1000) // add single elements.. i.e. not slice for i := 0; i < len(nums); i++ { heap.Add(&heaper{nums[i]}) } sort.SortInts(nums) for i := 0; i < len(nums); i++ { if heap.Remove().Priority() != nums[i] { t.Fatalf("binheap: Priority() != %d\n", nums[i]) } } }
// unique returns the list sorted and with duplicate entries removed func unique(list []int) []int { sort.SortInts(list) var last int i := 0 for _, x := range list { if i == 0 || x != last { last = x list[i] = x i++ } } return list[0:i] }
func Usage() { fmt.Fprintf(os.Stderr, "Use: %s [options] <command> [options] [args]\n", self) fmt.Fprint(os.Stderr, usage1) flag.PrintDefaults() fmt.Fprintln(os.Stderr) fmt.Fprintln(os.Stderr, "Exit Status (not an exhaustive list):") fmt.Fprintf(os.Stderr, " %3d: %s\n", 0, "success") var ns []int for n := range proto.Response_Err_name { ns = append(ns, int(n)) } sort.SortInts(ns) for _, n := range ns { name := proto.Response_Err_name[int32(n)] switch name { // These errors should never be exposed to the user, // so don't show them in the usage output. case "TAG_IN_USE", "UNKNOWN_VERB", "REDIRECT", "INVALID_SNAP": continue } var s string switch name { case "NOTDIR": s = "not a directory" case "ISDIR": s = "is a directory" default: s = strings.Replace(strings.ToLower(name), "_", " ", -1) } fmt.Fprintf(os.Stderr, " %3d: %s\n", n, s) } fmt.Fprint(os.Stderr, usage2) var max int var names []string us := make(map[string]string) for k := range cmds { u := k + " " + cmds[k].a if len(u) > max { max = len(u) } names = append(names, k) us[k] = u } sort.SortStrings(names) for _, k := range names { fmt.Fprintf(os.Stderr, " %-*s - %s\n", max, us[k], cmds[k].d) } }
func verifyElements(tree *RBTree, a []int, t *testing.T) { c := make([]int, len(a)) copy(c, a) sort.SortInts(c) index := 0 tree.For(func(e interface{}) bool { i := e.(int) if i != c[index] { t.Errorf("Expected %d, Actual %d", c[index], i) return false } index++ return true }) }
func generateDivisors(expandedProduct []int) []int { resultMap := make(map[int]bool) generateDivisorsRecursively(expandedProduct, 1, 0, resultMap) ret := make([]int, len(resultMap)) i := 0 for k, _ := range resultMap { ret[i] = k i += 1 } sort.SortInts(ret) return ret[:len(ret)-1] }
func (s *S) TestDistinct(c *C) { session, err := mgo.Mongo("localhost:40001") c.Assert(err, IsNil) defer session.Close() coll := session.DB("mydb").C("mycoll") for _, i := range []int{1, 4, 6, 2, 2, 3, 4} { coll.Insert(M{"n": i}) } var result []int err = coll.Find(M{"n": M{"$gt": 2}}).Sort(M{"n": 1}).Distinct("n", &result) sort.SortInts(result) c.Assert(result, Equals, []int{3, 4, 6}) }
func fmtRuns(rs map[int64]*run) (s string) { var ns []int for i := range rs { ns = append(ns, int(i)) } sort.SortInts(ns) for _, i := range ns { r := rs[int64(i)] if r.l.done { s += "X" } else if r.prop { s += "o" } else { s += "." } } return s }
func testLookups(t *testing.T, src string, x *Index, tc *testCase, n int) { for _, s := range tc.lookups { res := x.Lookup([]byte(s), n) exp := find(tc.source, s, n) // check that the lengths match if len(res) != len(exp) { t.Errorf("test %q, lookup %q (n = %d): expected %d results; got %d", tc.name, s, n, len(exp), len(res)) } // if n >= 0 the number of results is limited --- unless n >= all results, // we may obtain different positions from the Index and from find (because // Index may not find the results in the same order as find) => in general // we cannot simply check that the res and exp lists are equal // check that there are no duplicates sort.SortInts(res) for i, r := range res { if i > 0 && res[i-1] == r { t.Errorf("test %q, lookup %q, result %d (n = %d): found duplicate index %d", tc.name, s, i, n, r) } } // check that each result is in fact a correct match for i, r := range res { if r < 0 || len(src) <= r { t.Errorf("test %q, lookup %q, result %d (n = %d): index %d out of range [0, %d[", tc.name, s, i, n, r, len(src)) } else if !strings.HasPrefix(src[r:], s) { t.Errorf("test %q, lookup %q, result %d (n = %d): index %d not a match", tc.name, s, i, n, r) } } if n < 0 { // all results computed - sorted res and exp must be equal for i, r := range res { e := exp[i] if r != e { t.Errorf("test %q, lookup %q, result %d: expected index %d; got %d", tc.name, s, i, e, r) continue } } } } }
func main() { pr, pw, _ := os.Pipe() defer pr.Close() r := bufio.NewReader(pr) w := bufio.NewWriter(os.Stdout) defer w.Flush() pid, _ := os.StartProcess("/bin/ps", []string{"ps", "-e", "-opid,ppid,comm"}, nil, "", []*os.File{nil, pw, nil}) defer os.Wait(pid, os.WNOHANG) pw.Close() child := make(map[int]*vector.IntVector) s, ok := r.ReadString('\n') // Discard the header line s, ok = r.ReadString('\n') for ok == nil { f := strings.Fields(s) if _, present := child[atoi(f[PPID])]; !present { v := new(vector.IntVector) child[atoi(f[PPID])] = v } // Save the child PIDs on a vector child[atoi(f[PPID])].Push(atoi(f[PID])) s, ok = r.ReadString('\n') } // Sort the PPIDs schild := make([]int, len(child)) i := 0 for k, _ := range child { schild[i] = k i++ } sort.SortInts(schild) // Walk throught the sorted list for _, ppid := range schild { fmt.Printf("Pid %d has %d child", ppid, child[ppid].Len()) if child[ppid].Len() == 1 { fmt.Printf(": %v\n", []int(*child[ppid])) } else { fmt.Printf("ren: %v\n", []int(*child[ppid])) } } }
func main() { var ar [5]int fmt.Println(ar) // nice trick to output all elements // arrays and pointers try_to_transform_array(ar) fmt.Println(ar) transform_array(&ar) fmt.Println(ar) // Arrays with initializing // first 3 elements ar2 := [5]int{1, 2, 3} fmt.Println(ar2) // random elements ar3 := [5]int{0: 1, 2: 3, 4: 5} fmt.Println(ar3) // without size specifying ar4 := [...]int{1, 2, 3, 4, 5} fmt.Println(ar4) // without size specifying and just 1 ellement ar5 := [...]int{4: 5} fmt.Println(ar5) // passing array litteral as argument to function ar6 := array_reversing(&[5]int{1, 2, 3, 4, 5}) fmt.Println(*ar6) // array functions // len - size ar7 := []int{1, 3, 2, 5, 1} fmt.Printf("Array size is %d\n", len(ar7)) // sorting sort.SortInts(ar7) fmt.Println(ar7) }
// Compute minimum, p percentil, median, average, 100-p percentil and maximum of values in data. func SixvalInt(data []int, p int) (min, lq, med, avg, uq, max int) { min, max = math.MaxInt32, math.MinInt32 sum, n := 0, len(data) if n == 0 { return } if n == 1 { min = data[0] lq = data[0] med = data[0] avg = data[0] uq = data[0] max = data[0] return } for _, v := range data { if v < min { min = v } if v > max { max = v } sum += v } avg = sum / n sort.SortInts(data) if n%2 == 1 { med = data[(n-1)/2] } else { med = (data[n/2] + data[n/2-1]) / 2 } lq = PercentilInt(data, p) uq = PercentilInt(data, 100-p) return }
// Generate description from ParsedOps func arrange(desc ParsedOps) @[email protected] { nops := len(desc) clist := make([]int, nops) codes := make(map[int]string, nops) sdesc := make(@[email protected], nops) // Extract codes for each message type i := 0 for op, spec := range desc { for _, atype := range spec { for argname, argtype := range atype { if argname == "code" { clist[i], _ = strconv.Atoi(argtype) codes[clist[i]] = op // Remove code from desc atype[argname] = "0", false i = i + 1 } } } } // Populate description i = 0 sort.SortInts(clist) for _, code := range clist { sdesc[i].Code = code sdesc[i].Name = codes[code] sdesc[i].Args = desc[codes[code]] i = i + 1 } return sdesc }
// FindAllIndex returns a sorted list of non-overlapping matches of the // regular expression r, where a match is a pair of indices specifying // the matched slice of x.Bytes(). If n < 0, all matches are returned // in successive order. Otherwise, at most n matches are returned and // they may not be successive. The result is nil if there are no matches, // or if n == 0. // func (x *Index) FindAllIndex(r *regexp.Regexp, n int) (result [][]int) { // a non-empty literal prefix is used to determine possible // match start indices with Lookup prefix, complete := r.LiteralPrefix() lit := []byte(prefix) // worst-case scenario: no literal prefix if prefix == "" { return r.FindAllIndex(x.data, n) } // if regexp is a literal just use Lookup and convert its // result into match pairs if complete { // Lookup returns indices that may belong to overlapping matches. // After eliminating them, we may end up with fewer than n matches. // If we don't have enough at the end, redo the search with an // increased value n1, but only if Lookup returned all the requested // indices in the first place (if it returned fewer than that then // there cannot be more). for n1 := n; ; n1 += 2 * (n - len(result)) /* overflow ok */ { indices := x.Lookup(lit, n1) if len(indices) == 0 { return } sort.SortInts(indices) pairs := make([]int, 2*len(indices)) result = make([][]int, len(indices)) count := 0 prev := 0 for _, i := range indices { if count == n { break } // ignore indices leading to overlapping matches if prev <= i { j := 2 * count pairs[j+0] = i pairs[j+1] = i + len(lit) result[count] = pairs[j : j+2] count++ prev = i + len(lit) } } result = result[0:count] if len(result) >= n || len(indices) != n1 { // found all matches or there's no chance to find more // (n and n1 can be negative) break } } if len(result) == 0 { result = nil } return } // regexp has a non-empty literal prefix; Lookup(lit) computes // the indices of possible complete matches; use these as starting // points for anchored searches // (regexp "^" matches beginning of input, not beginning of line) r = regexp.MustCompile("^" + r.String()) // compiles because r compiled // same comment about Lookup applies here as in the loop above for n1 := n; ; n1 += 2 * (n - len(result)) /* overflow ok */ { indices := x.Lookup(lit, n1) if len(indices) == 0 { return } sort.SortInts(indices) result = result[0:0] prev := 0 for _, i := range indices { if len(result) == n { break } m := r.FindIndex(x.data[i:]) // anchored search - will not run off // ignore indices leading to overlapping matches if m != nil && prev <= i { m[0] = i // correct m m[1] += i result = append(result, m) prev = m[1] } } if len(result) >= n || len(indices) != n1 { // found all matches or there's no chance to find more // (n and n1 can be negative) break } } if len(result) == 0 { result = nil } return }
func BenchmarkStdlibSortInts(b *testing.B) { for i := 0; i < b.N; i++ { nums := randomInts(1000) sort.SortInts(nums) } }
func recursive(a, b map[int]bool, lastA, lastB int, results map[string]bool) { if len(a) < 6 { for i := lastA + 1; i < 10; i += 1 { if _, ok := a[i]; ok == true { continue } else { tmpA := make(map[int]bool) for k, v := range a { tmpA[k] = v } tmpA[i] = true recursive(tmpA, b, i, lastB, results) } } } if len(b) < 6 { for i := lastB + 1; i < 10; i += 1 { if _, ok := b[i]; ok == true { continue } else { tmpB := make(map[int]bool) for k, v := range b { tmpB[k] = v } tmpB[i] = true recursive(a, tmpB, lastA, i, results) } } } if len(a) == 6 && len(b) == 6 { if check(a, b) { str1, str2 := "", "" for k, _ := range a { str1 += fmt.Sprint(k) } for k, _ := range b { str2 += fmt.Sprint(k) } _, ok1 := results[str1+str2] _, ok2 := results[str2+str1] if ok1 == false && ok2 == false { results[str1+str2] = true str2 := "" vectorA := make([]int, 6) i := 0 for k, _ := range a { vectorA[i] = k i += 1 } vectorB := make([]int, 6) j := 0 for k, _ := range b { vectorB[j] = k j += 1 } sort.SortInts(vectorA) sort.SortInts(vectorB) for _, v := range vectorA { str2 += fmt.Sprint(v) } str2 += "," for _, v := range vectorB { str2 += fmt.Sprint(v) } fmt.Println(str2, len(results)) } } } }
func main() { fmt.Println() min := 2 max := 15000 kToProductSum := make([]int, 12000+1) for k, _ := range kToProductSum { kToProductSum[k] = 0x7fffffff } factorizedNumbers := generateAllNumbers(min, max) for number, factorization := range factorizedNumbers { expandedProduct := expandFactorization(factorization) sort.SortInts(expandedProduct) fmt.Println(number, "==", expandedProduct) products := generateEquivalentProducts(expandedProduct) for _, product := range products { k := isProductSum(product) fmt.Println(" ", k, product) if k <= 12000 { if kToProductSum[k] > number { kToProductSum[k] = number } } } } productSums := make(map[int]bool) for k, v := range kToProductSum { if k == 0 || k == 1 { continue } fmt.Println(k, v) productSums[v] = true } sumOfProductSums := uint64(0) for k, _ := range productSums { if k < 0 { panic("w00t") } sumOfProductSums += uint64(k) } fmt.Println(sumOfProductSums) }