本文整理汇总了Golang中sort.SearchInts函数的典型用法代码示例。如果您正苦于以下问题:Golang SearchInts函数的具体用法?Golang SearchInts怎么用?Golang SearchInts使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了SearchInts函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: fetch
func (it *SieveIterator) fetch(pageSize int, pageToken string) (string, error) {
start := 2
if pageToken != "" {
s, err := strconv.Atoi(pageToken)
if err != nil || s < 2 {
return "", fmt.Errorf("invalid token %q", pageToken)
}
start = s
}
if pageSize == 0 {
pageSize = 20 // Default page size.
}
// Make sure sufficient primes have been calculated.
it.calc(start + pageSize)
// Find the subslice of primes which match this page.
// Note that PageInfo requires that fetch does not remove any existing items,
// so we cannot assume that items is empty at this call.
items := it.p[sort.SearchInts(it.p, start):]
items = items[:sort.SearchInts(items, start+pageSize)]
it.items = append(it.items, items...)
if it.max > 0 && start+pageSize > it.max {
return "", nil // No more possible numbers to return.
}
return strconv.Itoa(start + pageSize), nil
}
示例2: LIS
// LIS is longest increasing subsequence
func LIS(seq []int) int {
dp := make([]int, len(seq))
for i := range dp {
dp[i] = math.MaxInt64
}
for _, n := range seq {
i := sort.SearchInts(dp, n)
dp[i] = n
}
return sort.SearchInts(dp, math.MaxInt64)
}
示例3: TestSearchSmall
func TestSearchSmall(t *testing.T) {
rand.Seed(0)
const limit = 10000
var ints []int
for i := 0; i < limit; i++ {
ints = append(ints, rand.Int())
}
sort.Ints(ints)
for want, q := range ints {
if idx := Search(ints, q); idx != want {
t.Errorf("Search(ints, %v)=%v, want %v", q, idx, want)
}
}
for i := 0; i < 10000; i++ {
q := rand.Int()
want := sort.SearchInts(ints, q)
if idx := Search(ints, q); idx != want {
t.Errorf("Search(ints, %v)=%v, want %v", q, idx, want)
}
}
}
示例4: IsPrime
// IsPrime is a primality test: it returns true if n is prime.
// It uses trial division to check whether n can be divided exactly by any
// number that is less than n.
// The algorithm can be very slow on large n despite a number of optimizations:
//
// * If n is relatively small, it is compared against a cached table of primes.
//
// * Only numbers up to sqrt(n) are used to check for primality.
//
// * n is first checked for divisibility by the primes in the cache and only if the test is inconclusive, n is checked against more numbers.
//
// * Only numbers of the form 6*k+|-1 that are greater than the last prime in the cache are checked after that.
//
// See https://en.wikipedia.org/wiki/Primality_test and
// https://en.wikipedia.org/wiki/Trial_division for details.
func IsPrime(n int) bool {
pMax := primes[len(primes)-1]
if n <= pMax {
// If n is prime, it must be in the cache
i := sort.SearchInts(primes, n)
return n == primes[i]
}
max := int(math.Ceil(math.Sqrt(float64(n))))
// Check if n is divisible by any of the cached primes
for _, p := range primes {
if p > max {
return true
}
if n%p == 0 {
return false
}
}
// When you run out of cached primes, check if n is divisible by
// any number 6*k+|-1 larger than the largest prime in the cache.
for d := (pMax/6+1)*6 - 1; d <= max; d += 6 {
if n%d == 0 || n%(d+2) == 0 {
return false
}
}
return true
}
示例5: primes
func primes() <-chan int {
c := make(chan int, 1)
cache := make([]int, 0)
isPrime := func(n int) bool {
for _, x := range cache[0 : sort.SearchInts(cache, int(math.Sqrt(float64(n))))+1] {
if n%x == 0 {
return false
}
}
return true
}
go func() {
c <- 2
cache = append(cache, 2)
for i := 3; ; i += 2 {
if isPrime(i) {
c <- i
cache = append(cache, i)
}
}
}()
return c
}
示例6: choose
// choose calculates (n k) or n choose k. Tolerant of quite large n/k.
func choose(n int, k int) int {
if k > n/2 {
k = n - k
}
numerator := make([]int, n-k)
denominator := make([]int, n-k)
for i, j := k+1, 1; i <= n; i, j = i+1, j+1 {
numerator[j-1] = int(i)
denominator[j-1] = j
}
if len(denominator) > 0 {
// find the first member of numerator not in denominator
z := sort.SearchInts(numerator, denominator[len(denominator)-1])
if z > 0 {
numerator = numerator[z+1:]
denominator = denominator[0 : len(denominator)-z-1]
}
}
for j := len(denominator) - 1; j > 0; j-- {
for i := len(numerator) - 1; i >= 0; i-- {
if numerator[i]%denominator[j] == 0 {
numerator[i] /= denominator[j]
denominator[j] = 1
break
}
}
}
f := 1
for _, i := range numerator {
f *= i
}
return f
}
示例7: validateBitType
func validateBitType(sqlType string, goType reflect.Type) bool {
bits := 0
if n, err := fmt.Sscanf(sqlType, "bit(%d)", &bits); err != nil {
return false
} else if n != 1 {
return false
}
requiredBits := []int{8, 16, 32, 64}
i := sort.SearchInts(requiredBits, bits)
if i >= len(requiredBits) {
return false
}
bits = requiredBits[i]
switch goType.Kind() {
case reflect.Int, reflect.Uint:
fallthrough
case reflect.Int8, reflect.Uint8:
fallthrough
case reflect.Int16, reflect.Uint16:
fallthrough
case reflect.Int32, reflect.Uint32:
fallthrough
case reflect.Int64, reflect.Uint64:
return bits == goType.Bits()
}
return false
}
示例8: Remove
// Remove removes an item from the set
func (s *Set) Remove(v int) bool {
if pos := sort.SearchInts(s.items, v); pos < len(s.items) && s.items[pos] == v {
s.items = s.items[:pos+copy(s.items[pos:], s.items[pos+1:])]
return true
}
return false
}
示例9: serveClients
func serveClients() {
level = data.LoadLevel(LevelFile)
frameCounter = 0
for { // while true
if len(clients) > 0 { // pause if no clients are connected
for _, k := range clientKeys {
id, client := k, clients[k]
if id > 0 {
oFrame := level.GetFrame(client.off, client.w, canvasX, frameCounter)
enc := gob.NewEncoder(client.con)
err := enc.Encode(oFrame)
if err != nil {
// client disconnected
//log.Println("BEFORE remove: clients:", clients, " clientKeys:", clientKeys)
// delete client
delete(clients, client.id)
// delete client key
// ugly as fuck in go to remove from a slice
// it *should* work though
idInKeys := sort.SearchInts(clientKeys, client.id)
clientKeys = append(clientKeys[:idInKeys], clientKeys[idInKeys+1:]...)
//log.Println("AFTER remove: clients:", clients, " clientKeys:", clientKeys)
resetServer()
}
//log.Println("ID:", id, "Client:", client)
}
}
frameCounter++
time.Sleep(time.Second / time.Duration(level.FPS))
}
}
}
示例10: Init
func (e *Equations) Init(n int, peq_notsorted []int) {
peq := make([]int, len(peq_notsorted))
copy(peq, peq_notsorted)
sort.Ints(peq)
e.N = n
e.N2 = len(peq)
e.N1 = e.N - e.N2
e.RF1 = make([]int, e.N1)
e.FR1 = make([]int, e.N)
e.RF2 = make([]int, e.N2)
e.FR2 = make([]int, e.N)
var i1, i2 int
for eq := 0; eq < n; eq++ {
e.FR1[eq] = -1 // indicates 'not set'
e.FR2[eq] = -1
idx := sort.SearchInts(peq, eq)
if idx < len(peq) && peq[idx] == eq { // found => prescribed
e.RF2[i2] = eq
e.FR2[eq] = i2
i2 += 1
} else { // not found => unknowns
e.RF1[i1] = eq
e.FR1[eq] = i1
i1 += 1
}
}
}
示例11: maybeEscapeOntoSubstring
/**
* Escapes the given range of the given sequence onto the given buffer iff it contains
* characters that need to be escaped.
* @return null if no output buffer was passed in, and s contains no characters that need
* escaping. Otherwise out, or a StringBuilder if one needed to be allocated.
*/
func (p *crossLanguageStringXform) maybeEscapeOntoSubstring(s string, out io.Writer, start, end int) (io.Writer, error) {
var err error
pos := start
escapesByCodeUnitLen := len(p.escapesByCodeUnit)
for j, c := range s[start:end] {
i := start + j
if int(c) < escapesByCodeUnitLen { // Use the dense map.
esc := p.escapesByCodeUnit[c]
if esc != "" {
if out == nil {
// Create a new buffer if we need to escape a character in s.
// We add 32 to the size to leave a decent amount of space for escape characters.
out = bytes.NewBuffer(make([]byte, 0))
}
_, err = io.WriteString(out, s[pos:i])
if err != nil {
return out, err
}
_, err = io.WriteString(out, esc)
if err != nil {
return out, err
}
pos = i + 1
}
} else if c >= 0x80 { // Use the sparse map.
index := sort.SearchInts(p.nonAsciiCodeUnits, int(c))
if index >= 0 {
if out == nil {
out = bytes.NewBuffer(make([]byte, 0))
}
_, err = io.WriteString(out, s[pos:i])
if err != nil {
return out, err
}
_, err = io.WriteString(out, p.nonAsciiEscapes[index])
if err != nil {
return out, err
}
pos = i + 1
} else if p.nonAsciiPrefix != "" { // Fallback to the prefix based escaping.
if out == nil {
out = bytes.NewBuffer(make([]byte, 0))
}
_, err = io.WriteString(out, s[pos:i])
if err != nil {
return out, err
}
err = p.escapeUsingPrefix(c, out)
if err != nil {
return out, err
}
pos = i + 1
}
}
}
if out != nil {
_, err = io.WriteString(out, s[pos:end])
}
return out, err
}
示例12: TestSearchBig
func TestSearchBig(t *testing.T) {
if testing.Short() {
t.Skip("Skipping big test search")
}
rand.Seed(0)
const maxLimit = 100e6
ints := make([]int, maxLimit)
for i := 0; i < maxLimit; i++ {
ints[i] = rand.Int()
}
sort.Ints(ints)
for i := 0; i < 100000000; i++ {
elt := rand.Int()
vidx := Search(ints, elt)
idx := sort.SearchInts(ints, elt)
if vidx != idx {
t.Fatalf("Search failed for elt=%d: got %d want %d\n", elt, vidx, idx)
}
}
}
示例13: remove
// remove removes the id from the list if it exists and returns a new list of ids.
func (s ids) remove(id int) ids {
index := sort.SearchInts([]int(s), id)
if index < len(s) && s[index] == id {
s = append(s[:index], s[index+1:]...)
}
return s
}
示例14: getScore
func (set *Set) getScore() int {
score := 0
matches := 0
for _, row := range *test_data {
matches = 0
// score += -1 //1 combination cost
for _, num := range *set {
n := sort.SearchInts(*row, num)
if n < len(*row) && (*row)[n] == num {
matches++
}
}
switch matches {
case 3:
score += 2
case 4:
score += 2 << 1
case 5:
score += 2 << 2
case 6:
score += 2 << 3
}
}
return score
}
示例15: IntUnique
// IntUnique returns a unique and sorted slice of integers
func IntUnique(slices ...[]int) (res []int) {
if len(slices) == 0 {
return
}
nn := 0
for i := 0; i < len(slices); i++ {
nn += len(slices[i])
}
res = make([]int, 0, nn)
for i := 0; i < len(slices); i++ {
a := make([]int, len(slices[i]))
copy(a, slices[i])
sort.Ints(a)
for j := 0; j < len(a); j++ {
idx := sort.SearchInts(res, a[j])
if idx < len(res) && res[idx] == a[j] {
continue // found
} else {
if idx == len(res) { // append
res = append(res, a[j])
} else { // insert
res = append(res[:idx], append([]int{a[j]}, res[idx:]...)...)
}
}
}
}
return
}