예제 #1
0
파일: main.go 프로젝트: jvillasante/algs4
// This program takes the name of a whitelist file (a sequence of integers) as argument and filters any
// entry that is on the whitelist from standard input, leaving only integers that are not on the whitelist
// on standard output. It uses the binary search algorithm, implemented in the method Rank(),
// to accomplish the task efficiently.
func main() {
	if len(os.Args) <= 1 {
		fmt.Printf("usage: %s tinyW.txt < tinyT.txt\n", filepath.Base(os.Args[0]))
		return
	}

	whitelist, err := in.ReadAllIntsFromFile(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}
	sort.Ints(whitelist)

	stdin := stdin.NewStdin()
	for !stdin.IsEmpty() {
		// Read key, print if not in whitelist
		key, err := stdin.ReadInt()
		if err != nil {
			log.Fatal(err)
		}

		if bsearch.Rank(key, whitelist) == -1 {
			fmt.Println(key)
		}
	}
}
예제 #2
0
// Count counts doubles that sum to 0 (ignoring integer overflow).
// This implementation takes linearithmic time
// Returns the number of doubles (i, j) with i < j such that a[i] + a[j] == 0.
// The improved algorithm is based on the fact that an entry a[i] is one of a pair that sums to
// 0 if and only if the value -a[i] is in the array (and a[i] is not zero). To solve the problem,
// we sort the array (to enable binary search) and then, for every entry a[i] in the array, do a
// binary search for -a[i] with Rank() in bsearch package. If the result is an index j with j > i,
// we increment the count.
func Count(a []int) int {
	sort.Ints(a)
	n := len(a)
	cnt := 0

	for i := 0; i < n; i++ {
		if bsearch.Rank(-a[i], a) > i {
			cnt++
		}
	}

	return cnt
}
예제 #3
0
// Count returns the number of triples (i, j, k) with i < j < k such that a[i] + a[j] + a[k] == 0.
// This implementation ignores integer overflow.
// This implementation uses sorting and binary search and takes time proportional to N^2 log N,
// where N is the number of integers.
func Count(a []int) int {
	sort.Ints(a)
	n := len(a)

	if containsDuplicates(a) {
		panic("array contains duplicate integers")
	}

	cnt := 0
	for i := 0; i < n; i++ {
		for j := i + 1; j < n; j++ {
			if bsearch.Rank(-(a[i]+a[j]), a) > j {
				cnt++
			}
		}
	}

	return cnt
}