Ejemplo n.º 1
0
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
}
Ejemplo n.º 2
0
Archivo: lis.go Proyecto: yukirin/algo
// 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)
}
Ejemplo n.º 3
0
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)
		}
	}
}
Ejemplo n.º 4
0
// 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
}
Ejemplo n.º 5
0
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
}
Ejemplo n.º 6
0
// 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
}
Ejemplo n.º 7
0
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
}
Ejemplo n.º 8
0
Archivo: intset.go Proyecto: bsm/intset
// 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
}
Ejemplo n.º 9
0
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 f**k 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))
		}
	}
}
Ejemplo n.º 10
0
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
		}
	}
}
/**
 * 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
}
Ejemplo n.º 12
0
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)
		}
	}
}
Ejemplo n.º 13
0
// 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
}
Ejemplo n.º 14
0
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
}
Ejemplo n.º 15
0
// 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
}
Ejemplo n.º 16
0
func main() {
	arr := []int{9, 8, 7, 6, 3, 2, 1}
	sort.Ints(arr)
	fmt.Printf("%v\n", arr)
	result := sort.SearchInts(arr, 5)
	fmt.Printf("%v\n", result)
}
Ejemplo n.º 17
0
func (h *host) allocateTCP(port uint16) (uint16, error) {
	h.mtx.Lock()
	defer h.mtx.Unlock()

	if len(h.TCP) == (math.MaxUint16 - 1) {
		return 0, errors.New("port pool depleted")
	}

	// Find next unused port
	var wrapCount = 0
	for port == 0 {
		if h.NextTCP >= math.MaxUint16 {
			h.NextTCP = 49152
			wrapCount++
			if wrapCount == 2 {
				return 0, errors.New("port pool depleted")
			}
		} else if h.NextTCP < 49152 {
			h.NextTCP = 49152
		} else {
			h.NextTCP++
		}

		if sort.SearchInts(h.TCP, h.NextTCP) == len(h.TCP) {
			port = uint16(h.NextTCP)
			break
		}
	}

	h.TCP = append(h.TCP, int(port))
	sort.Ints(h.TCP)

	return port, nil
}
Ejemplo n.º 18
0
func (expr *Expression) nextMonth(t time.Time) time.Time {
	// Find index at which item in list is greater or equal to
	// candidate month
	i := sort.SearchInts(expr.monthList, int(t.Month())+1)
	if i == len(expr.monthList) {
		return expr.nextYear(t)
	}
	// Month changed, need to recalculate actual days of month
	expr.actualDaysOfMonthList = expr.calculateActualDaysOfMonth(t.Year(), expr.monthList[i])
	if len(expr.actualDaysOfMonthList) == 0 {
		return expr.nextMonth(time.Date(
			t.Year(),
			time.Month(expr.monthList[i]),
			1,
			expr.hourList[0],
			expr.minuteList[0],
			expr.secondList[0],
			0,
			t.Location()))
	}

	return time.Date(
		t.Year(),
		time.Month(expr.monthList[i]),
		expr.actualDaysOfMonthList[0],
		expr.hourList[0],
		expr.minuteList[0],
		expr.secondList[0],
		0,
		t.Location())
}
Ejemplo n.º 19
0
func DeleteItem(inta myint, val int) []int {
	if len(inta) == 0 {
		return inta
	}
	sort.Sort(inta)
	i := sort.SearchInts(inta, val)
	return append(inta[:i], inta[i+1:]...)
}
Ejemplo n.º 20
0
func upperBoundInts(ints []int, x int) int {
	i := sort.SearchInts(ints, x)
	for i < len(ints) && ints[i] == x {
		i++
	}

	return i
}
Ejemplo n.º 21
0
func lowerBoundInts(ints []int, x int) int {
	i := sort.SearchInts(ints, x)
	for i > 0 && ints[i-1] == x {
		i--
	}

	return i
}
Ejemplo n.º 22
0
Archivo: errors.go Proyecto: mewmew/uc
// Position returns the corresponding line:column pair of the given position in
// the input stream.
func (src *Source) Position(pos int) (line, column int) {
	// Implemented using binary search, lines should be sorted in ascending
	// order.
	index := sort.SearchInts(src.Lines, pos+1) - 1
	line = index + 1
	column = pos - src.Lines[index] + 1
	return line, column
}
Ejemplo n.º 23
0
func expandCluster(data []Point, cluster []int, seen []pointStatus, epsilon float64) []int {
	tmp := []int(nil)
	for i := range data {
		if seen[i] == _Cluster {
			if sort.SearchInts(cluster, i) == len(cluster) || sort.SearchInts(tmp, i) == len(tmp) {
				for _, j := range cluster {
					if withinEpsilon(data[i], data[j], epsilon) {
						tmp = append(tmp, i)
						seen[i] = _Cluster
					} else {
						seen[i] = _Noise
					}
				}
			}
		}
	}
	return merge(cluster, tmp)
}
Ejemplo n.º 24
0
func (this *ArrayList) Find(docid int) (err error) {
	subLen := len(this.docIds) - this.curPos
	searchRes := sort.SearchInts(this.docIds[this.curPos:], docid)
	if searchRes < subLen {
		return nil
	} else {
		return fmt.Errorf("can not find docid[%d]", docid)
	}
}
Ejemplo n.º 25
0
Archivo: lis.go Proyecto: srid/lislen
func (lis *LIS) findIdx(num int) int {
	// on a mostly sorted array, check the last bucket before doing binary search.
	bLen := len(lis.bucket)
	if bLen > 0 && lis.bucket[bLen-1] < num {
		return bLen
	} else {
		return sort.SearchInts(lis.bucket, num)
	}
}
Ejemplo n.º 26
0
// appends x to array of ints
func appendIntIfNotExists(aPtr *[]int, x int) {
	a := *aPtr
	if sort.SearchInts(a, x) >= 0 {
		return
	}
	a = append(a, x)
	sort.Ints(a)
	*aPtr = a
}
Ejemplo n.º 27
0
func (t *MedianAnalyzer) addUniqueCount(count int) {
	// Search for proper place
	i := sort.SearchInts(t.UniqueCounts, count)

	// insert value
	t.UniqueCounts = append(t.UniqueCounts, 0)
	copy(t.UniqueCounts[i+1:], t.UniqueCounts[i:])
	t.UniqueCounts[i] = count
}
Ejemplo n.º 28
0
func (b *Broker) isPartitionBlocked(partition int) bool {
	if b.nWriteDisabledPartitions == 0 {
		return false
	}
	idx := sort.SearchInts(b.writeDisabledPartitions, partition)
	if b.writeDisabledPartitions[idx] == partition {
		return true
	}
	return false
}
Ejemplo n.º 29
0
func (w *WaitSet) check(i, idx, prev int) bool {
	if w.wait[idx] == nil {
		return true
	}
	j := sort.SearchInts(w.wait[idx], i-prev)
	if j == len(w.wait[idx]) || w.wait[idx][j] != i-prev {
		return false
	}
	return true
}
Ejemplo n.º 30
0
func (s *Set) Remove(n int) {
	s.mu.Lock()
	defer s.mu.Unlock()
	i := sort.SearchInts(s.m, n)
	if i == len(s.m) || s.m[i] != n {
		return
	}
	copy(s.m[i+1:], s.m[i:])
	s.m = s.m[:len(s.m)-1]
}