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) } } }
func writeGff3(chromMapDict map[string]*ContigMap, comparisonMethod *string) { for chrom, value := range chromMapDict { // Open a file-handle for this chromosome var ( chromFh *os.File err error f string = chrom + OutputSuffix ) log.Println("Writing gff3 for", f) // Try to create the file if chromFh, err = os.Create(f); err != nil { log.Fatal(err) } currentContig := value.firstContig chromFh.WriteString("##gff-version3\n") // TODO: Find a way to replace the -1. Not easy and not important. chromFh.WriteString("##sequence-region " + currentContig.chromosome + " 1 -1\n") for currentContig != nil { lineSlice := getGff3Line(currentContig) chromFh.WriteString(strings.Join(lineSlice, "\t") + "\n") if len(currentContig.dictOfPartners) > 0 { // We can place unplaced contigs here! // sort the keys of the dictOfPartners by score scores := make([]float64, len(currentContig.dictOfPartners)) i := 0 for key, _ := range currentContig.dictOfPartners { scores[i] = key i++ } // With Hamming, the lowest score is the best, so normal sorting is alright - in all other cases, high is better, so we have to invert if *comparisonMethod == "hamming" { // sort by lowest to highest sort.Sort(sort.Float64Slice(scores)) } else { sort.Sort(sort.Reverse(sort.Float64Slice(scores))) } // Each value for the keys is a slice of contigs - we can't sort these, so keep them the way they showed up // In 99.9999% of cases the slice has only one contig for _, score := range scores { contigs := currentContig.dictOfPartners[score] for _, c := range contigs { lineSlice := getGff3Line(c) chromFh.WriteString(strings.Join(lineSlice, "\t") + "\n") } } } currentContig = currentContig.nextContig } } }
func main() { files, _ := ioutil.ReadDir("../") sort.Sort(ByTime(files)) for i := 0; i < len(files); i++ { fmt.Println(files[i].ModTime()) // 2015-08-10 14:43:35 +0800 CST // 2015-08-10 16:03:25 +0800 CST // ... } d := []int{5, 2, 4, 6, 5, 5, 1, 11, 43, 0, -1} sort.Sort(sort.IntSlice(d)) fmt.Println(d) // [-1 0 1 2 4 5 5 5 6 11 43] a := []float64{1.2, -1, 0.0, 1.0, 89.2, 0.0001, 1.2345} sort.Sort(sort.Float64Slice(a)) fmt.Println(a) // [-1 0 0.0001 1 1.2 1.2345 89.2] s := []string{"PHP", "go", "Go", "java", "python", "c"} sort.Sort(sort.StringSlice(s)) fmt.Println(s) // [Go PHP c go java python] fruits := []string{"peach", "banana", "kiwi"} sort.Sort(ByLenth(fruits)) fmt.Println(fruits) // [banana kiwi peach] }
func (self *DB) Zsort(name string) { // //self.mu.Lock() values := make([]float64, len(self.zmp[name])) tm := make(map[float64][]NF, len(self.zmp[name])) for i := 0; i < len(self.zmp[name]); i += 1 { value := self.zmp[name][i].Value values[i] = value tm[value] = append(tm[value], self.zmp[name][i]) } a := sort.Float64Slice(values[0:]) sort.Sort(a) var temp []NF var old float64 for i := 0; i < len(a); i += 1 { if old != a[i] { temp = append(temp, tm[a[i]]...) } old = a[i] } self.zmp[name] = temp //self.mu.Unlock() }
func TestSVD_vsEig(t *testing.T) { m, n := 150, 100 a := randMat(m, n) g := mat.Mul(mat.T(a), a) // Take eigen decomposition of Gram matrix. _, eigs, err := EigSymm(g) if err != nil { t.Fatal(err) } // Sort in descending order. sort.Sort(sort.Reverse(sort.Float64Slice(eigs))) // Take square root of eigenvalues. for i := range eigs { // Clip small negative values to zero. eigs[i] = math.Sqrt(math.Max(0, eigs[i])) } // Take singular value decomposition. _, svals, _, err := SVD(a) if err != nil { t.Fatal(err) } testSliceEq(t, eigs, svals) }
func (nv *NearestValueThreshold) compute(data map[string]float64, total int) (float64, error, string) { var err error var msg string testValue := float64(0) testFloat, err := strconv.ParseFloat(nv.Value, 64) if err != nil { msg = fmt.Sprintf("Error converting value to float: %s", err) logrus.Error(msg) return testValue, err, msg } fm, _ := numeric.ND_Mapper(data) keys := fm.FloatSlice m := fm.Float2String sort.Sort(sort.Float64Slice(keys)) for _, k := range keys { if testFloat >= k { testValue = data[m[k]] } else { break } } testValue = testValue * 100 return testValue, err, msg }
func main() { intList := []int{2, 4, 3, 5, 7, 6, 9, 8, 1, 0} float8List := []float64{4.2, 5.9, 12.3, 10.0, 50.4, 99.9, 31.4, 27.81828, 3.14} stringList := []string{"a", "c", "b", "d", "f", "i", "z", "x", "w", "y"} fmt.Println("------------正序---------------") sort.Ints(intList) sort.Float64s(float8List) sort.Strings(stringList) fmt.Printf("%v\n%v\n%v\n", intList, float8List, stringList) fmt.Println("------------倒序---------------") sort.Sort(sort.Reverse(sort.IntSlice(intList))) sort.Sort(sort.Reverse(sort.Float64Slice(float8List))) sort.Sort(sort.Reverse(sort.StringSlice(stringList))) fmt.Printf("%v\n%v\n%v\n", intList, float8List, stringList) fmt.Println("-------------结构体(特定字段)排序-----------") people := []Person{ {"zhang san", 12}, {"li si", 30}, {"wang wu", 52}, {"zhao liu", 26}, } fmt.Println(people) sort.Sort(PersonWrapper{people, func(p, q *Person) bool { return q.Age < p.Age //Age 递减排序 }}) fmt.Println(people) sort.Sort(PersonWrapper{people, func(p, q *Person) bool { return p.Name < q.Name //Name 递增排序 }}) fmt.Println(people) }
func (bc *BayesianClassifier) filteredProbabilities(tokens []string, categories []string) (map[string][]float64, error) { probs, err := bc.probabilities(tokens, categories) if err != nil { return nil, err } for cat, pr := range probs { if bc.MinProbabilityStrength > 0.0 { i := 0 for i < len(pr) { dist := math.Abs(pr[i] - 0.5) if dist >= bc.MinProbabilityStrength { i++ } else { if i == len(pr)-1 { pr = pr[:len(pr)-1] break } pr[i] = pr[len(pr)-1] pr = pr[:len(pr)-1] } } } if bc.MaxDiscriminators > 0 && len(pr) > bc.MaxDiscriminators { sort.Sort(sort.Float64Slice(pr)) pr = pr[:bc.MaxDiscriminators] } probs[cat] = pr } return probs, nil }
//NEAREST RANK METHOD (USES ONLY MEMBERS OF POPULATION - NO INTERPOLATION) func (p *Percentile) Finalize() error { p.result = make(map[string]float64) fm, _ := numeric.ND_Mapper(p.counts) keys := fm.FloatSlice m := fm.Float2String totalFloat := fm.TotalFloat sort.Sort(sort.Float64Slice(keys)) for c := float64(0); c < 100; c++ { threshold := totalFloat * c / 100 sum := float64(0) //keep index of key coorsponding to last sum var i int var k float64 for i, k = range keys { sum += p.counts[m[k]] if sum >= threshold { break } } p.result[strconv.FormatFloat(c, 'f', -1, 64)] = keys[i] } return nil }
// Export the set of values in the Ring Buffer, where the latest value // will be last in the array. If the Buffer was not full, 0 will be exported. func (buf *RingBuffer) Export() []float64 { buf.mu.Lock() defer buf.mu.Unlock() length := len(buf.values) data := make([]float64, length) idx := 0 for i := buf.oldest; i < len(buf.values); i++ { v := buf.values[i] if v != nil { data[idx] = *v idx++ } } for i := 0; i < buf.oldest; i++ { v := buf.values[i] if v != nil { data[idx] = *v idx++ } } sort.Reverse(sort.Float64Slice(data)) shrink := make([]float64, idx) copy(shrink, data) return shrink }
func doloop() { var f0 float64 // Nominal lens focal length var fm float64 // Focal length at minimum focus distance var md float64 // Minimum focus distance w/out extension var err error // Error return var exlist []float64 flag.Parse() if flag.NArg() < 3 { println("Sorry, need 3+ args") return } f0, err = strconv.ParseFloat(flag.Arg(0), 64) if err != nil { println("Sorry - bad focal length") return } md, err = strconv.ParseFloat(flag.Arg(1), 64) if err != nil { println("Sorry - bad minimum distance") return } exlist = getext() sort.Sort(sort.Reverse(sort.Float64Slice(exlist))) mdm := 1000 * md fm = f0 * (mdm - f0) / mdm fmt.Printf("Lens: %5.0f mm, Min focus: %0.3f m, Fmin %0.1f mm\n", f0, md, fm) calcext(exlist, f0, fm) return }
// BinarySuffix returns the given number with a binary suffix. func BinarySuffix(number float64) string { var str string if number < 0 { str = "-" number = math.Abs(number) } var binarySuffixPrefixes = map[float64]string{ 1125899906842624: "%.2f PB", 1099511627776: "%.2f TB", 1073741824: "%.2f GB", 1048576: "%.2f MB", 1024: "%.1f kB", } intSlice := make([]float64, 0, len(binarySuffixPrefixes)) for num := range binarySuffixPrefixes { intSlice = append(intSlice, num) } sort.Sort(sort.Reverse(sort.Float64Slice(intSlice))) for _, size := range intSlice { if size <= number { var value float64 if number >= BinaryConvertThreshold { value = number / float64(size) } return str + fmt.Sprintf(binarySuffixPrefixes[size], value) } } return fmt.Sprintf("%s%.0f bytes", str, number) }
func NewSlice(n []float64) *Slice { s := &Slice{Float64Slice: sort.Float64Slice(n), idx: make([]int, len(n))} for i := range s.idx { s.idx[i] = i } return s }
func (h *Histogram) Percentiles(percentiles ...float64) []int { result := make([]int, len(percentiles)) if percentiles == nil || len(percentiles) == 0 { return result } sort.Sort(sort.Float64Slice(percentiles)) accum := 0 p_idx := int(math.Max(1.0, percentiles[0]*float64(h.n))) for i, j := 0, 0; i < len(percentiles) && j < len(h.values); j++ { accum += h.values[j] for accum >= p_idx { result[i] = j i++ if i >= len(percentiles) { break } p_idx = int(math.Max(1.0, percentiles[i]*float64(h.n))) } } return result }
// Float64StableSum returns the sum of the elements of the given []float64 // in a relatively stable manner. func Float64StableSum(s []float64) float64 { sort.Sort(sort.Float64Slice(s)) sum := 0.0 for _, elem := range s { sum += elem } return sum }
// SupportedVersions will return a slice of supported SPDY versions. // The returned versions are sorted into order of most recent first. func SupportedVersions() []float64 { s := make([]float64, 0, len(supportedVersions)) for v, _ := range supportedVersions { s = append(s, v) } sort.Sort(sort.Reverse(sort.Float64Slice(s))) return s }
func TestFloat64s(t *testing.T) { data := float64s Sort(sort.Float64Slice(data[0:])) if !sort.Float64sAreSorted(data[0:]) { t.Errorf("sorted %v", float64s) t.Errorf(" got %v", data) } }
func TestSortFloat64Slice(t *testing.T) { data := float64s a := sort.Float64Slice(data[0:]) Sort(a) if !sort.IsSorted(a) { t.Errorf("sorted %v", float64s) t.Errorf(" got %v", data) } }
func withinError(t *testing.T, fn Estimate, q, e float64) func(N uint32) bool { return func(N uint32) bool { n := int(N % 1000000) est := New(fn) obs := make([]float64, 0, n) for i := 0; i < n; i++ { s := rand.NormFloat64()*1.0 + 0.0 obs = append(obs, s) est.Add(s) } if est.Samples() != n { return false } sort.Float64Slice(obs).Sort() // "v" the estimate estimate := est.Get(q) if n == 0 { return estimate == 0 } // A[⌈(φ − ε)n⌉] ≤ v ≤ A[⌈(φ + ε)n⌉] // The bounds of the estimate lower := int((q-e)*float64(n)) - 1 upper := int((q+e)*float64(n)) + 1 // actual v exact := int(q * float64(n)) min := obs[0] if lower > 0 { min = obs[lower] } max := obs[len(obs)-1] if upper < len(obs) { max = obs[upper] } t.Logf("delta: %d ex: %f min: %f (%f) max: %f (%f) est: %f n: %d l: %d", upper-lower, obs[exact], min, obs[0], max, obs[len(obs)-1], estimate, n, est.items) fits := (min <= estimate && estimate <= max) if !fits { for cur := est.head; cur != nil; cur = cur.next { t.Log(cur) } } return fits } }
// Splits lines into groups of 10 with score of how much linearly distributed they are func linearDistances(lines []polarLine, dividerLine polarLine) []scoredLines { // Lines have to be sorted correctly! var matches []scoredLines linesCount := len(lines) if linesCount < 10 { return matches } intersections := make([]image.Point, linesCount, linesCount) for i, line := range lines { _, point := intersection(line, dividerLine) intersections[i] = point } points := make([]float64, len(lines), len(lines)) for i, point := range intersections { points[i] = distanceBetweenPoints(intersections[0], point) } distances := preparePointDistances(points) expectedPoints := make([]float64, 10, 10) for i := range points[:linesCount-10+1] { dI := i + 10 - 1 for j := range points[dI:] { start, end := points[i], points[j+dI] step := (end - start) / 9.0 for k := range expectedPoints { expectedPoints[k] = start + step*float64(k) } score, selectedPoints := pointSimilarities(expectedPoints, distances) if len(selectedPoints) != 10 { continue } match := scoredLines{ Score: score, Lines: make([]polarLine, 10, 10), } searchablePoints := sort.Float64Slice(points) for l := range match.Lines { match.Lines[l] = lines[searchablePoints.Search(selectedPoints[l])] } matches = append(matches, match) } } return matches }
func main() { a := []int{10, 5, 3, 7, 6} b := []float64{4.2, 7.6, 5.5, 1.3, 9.9} c := []string{"Maria", "Andrew", "John"} sort.Sort(sort.IntSlice(a)) // int 슬라이스를 오름차순으로 정렬 fmt.Println(a) sort.Sort(sort.Reverse(sort.IntSlice(a))) // int 슬라이스를 내림차순으로 정렬 fmt.Println(a) sort.Sort(sort.Float64Slice(b)) // float64 슬라이스를 오름차순으로 정렬 fmt.Println(b) sort.Sort(sort.Reverse(sort.Float64Slice(b))) // float64 슬라이스를 내림차순으로 정렬 fmt.Println(b) sort.Sort(sort.StringSlice(c)) // string 슬라이스를 오름차순으로 정렬 fmt.Println(c) sort.Sort(sort.Reverse(sort.StringSlice(c))) // string 슬라이스를 내림차순으로 정렬 fmt.Println(c) }
// Dlasrt sorts the numbers in the input slice d. If sort == lapack.SortIncreasing, // the elements are sorted in increasing order. If sort == lapack.SortDecreasing, // the elements are sorted in decreasing order. // // Dlasrt is an internal routine. It is exported for testing purposes. func (impl Implementation) Dlasrt(s lapack.Sort, n int, d []float64) { checkVector(n, d, 1) d = d[:n] switch s { default: panic("lapack: bad sort") case lapack.SortIncreasing: sort.Float64s(d) case lapack.SortDecreasing: sort.Sort(sort.Reverse(sort.Float64Slice(d))) } }
func (ks *KS) compute(data map[string]float64, total int) (float64, error, string) { var err error var msg string testValue := float64(0) fm_data, _ := numeric.ND_Mapper(data) keys_data := fm_data.FloatSlice map_data := fm_data.Float2String totalZero := fm_data.TotalFloat benchmark, err := histogram.GetFloatMap(ks.BenchmarkJSON) if err != nil { msg = fmt.Sprintf("Error in benchmark float map: %s", err) logrus.Error(msg) return testValue, err, msg } fm_benchmark, err := numeric.ND_Mapper(benchmark) if err != nil { msg = fmt.Sprintf("Error in mapping benchmark to NumericDistribution: %s", err) logrus.Error(msg) return testValue, err, msg } keys_benchmark := fm_benchmark.FloatSlice map_benchmark := fm_benchmark.Float2String totalOne := fm_benchmark.TotalFloat key_map, keys_all := arrayMapper(keys_data, keys_benchmark) sort.Sort(sort.Float64Slice(keys_all)) zeroSoFar := float64(0) oneSoFar := float64(0) currentKS := math.NaN() maxKS := float64(0) for _, f := range keys_all { if key_map[f][0] { zeroSoFar += data[map_data[f]] } if key_map[f][1] { oneSoFar += benchmark[map_benchmark[f]] } currentKS = (zeroSoFar / totalZero) - (oneSoFar / totalOne) if math.Abs(currentKS) > math.Abs(maxKS) || math.IsNaN(currentKS) { maxKS = currentKS } } testValue = maxKS * 100 return testValue, err, msg }
func TestSortFloat64Slice(t *testing.T) { data := float64s for _, alg := range algorithms { a := sort.Float64Slice(data[:]) alg(a) if !sort.IsSorted(a) { t.Errorf("%v\n", util.GetFuncName(alg)) t.Errorf("sorted: %v\n", float64s) t.Errorf(" got: %v\n", data) } } }
/*KindFromSides determines the type of triangle formed by sides a, b and c the triangle is invaid if the longest side is equal or longer than the shorter sides or any of the sides are invalid (0 or less, NaN or Inf+)*/ func KindFromSides(a, b, c float64) Kind { sides := []float64{a, b, c} sort.Sort(sort.Float64Slice(sides)) switch { case math.IsNaN(sides[0]) || sides[0] <= 0 || sides[2] == math.Inf(1) || sides[1]+sides[0] <= sides[2]: return NaT case sides[0] == sides[1] && sides[1] == sides[2]: return Equ case sides[0] == sides[1] || sides[1] == sides[2]: return Iso } return Sca }
func main() { var n int fmt.Scanln(&n) w := make([]float64, n) for i := 0; i < n; i++ { fmt.Scanln(&w[i]) } for n > 1 { sort.Sort(sort.Float64Slice(w)) val := 2 * math.Sqrt(w[n-2]*w[n-1]) n-- w = w[:n] w[n-1] = val } fmt.Println(w[0]) }
func (cdf *CDF) Finalize() error { cdf.result = make(map[string]float64) fm, _ := numeric.ND_Mapper(cdf.counts) keys := fm.FloatSlice m := fm.Float2String totalFloat := fm.TotalFloat sort.Sort(sort.Float64Slice(keys)) sum := float64(0) for _, f := range keys { sum += cdf.counts[m[f]] cdf.result[m[f]] = sum / totalFloat } return nil }
func ExampleEigSymm() { a := mat.NewRows([][]float64{ {7, -2, 0}, {-2, 6, -2}, {0, -2, 5}, }) _, d, err := EigSymm(a) if err != nil { fmt.Println(err) return } sort.Sort(sort.Float64Slice(d)) fmt.Printf("%.6g\n", d) // Output: // [3 6 9] }
// NewDataset constructs a dataset from the provided records. The records can be // provided in any order and are automatically sorted (but NOT de-duplicated). // If no records are provided, this function will return nil. func NewDataset(records ...float64) *Dataset { if len(records) == 0 { return nil } slice := sort.Float64Slice(records) slice.Sort() d := &Dataset{ records: []float64(slice), len: len(records), } d.min = d.records[0] d.max = d.records[d.len-1] for _, record := range d.records { d.sum = d.sum + record } return d }
func (r *SVGReport) drawDurationsHistogram(report *Report) int { waitTimes := []float64{} for _, start := range report.AuctionResults.SuccessfulLRPs { waitTimes = append(waitTimes, start.WaitDuration.Seconds()) } sort.Sort(sort.Float64Slice(waitTimes)) bins := binUp([]float64{0, 0.25, 0.5, 1, 2, 5, 10, 20, 40, 1e9}, waitTimes) labels := []string{"<0.25s", "0.25-0.5s", "0.5-1s", "1-2s", "2-5s", "5-10s", "10-20s", "20-40s", ">40s"} r.SVG.Translate(border*2+instanceBoxWidth, border) yBottom := r.drawHistogram(bins, labels) r.SVG.Gend() return yBottom + border //'cause of the translate }