github.com/aclements/go-misc@v0.0.0-20240129233631-2f6ede80790c/go-weave/amb/rand.go (about)

     1  // Copyright 2016 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package amb
     6  
     7  import "math/rand"
     8  
     9  // StrategyRandom explores the ambiguous value space randomly. It
    10  // makes no attempt to avoid repeatedly visiting the same point, nor
    11  // does it know when it has explored the entire space.
    12  type StrategyRandom struct {
    13  	// MaxDepth specifies the maximum depth of the tree. If this
    14  	// is 0, it defaults to DefaultMaxDepth.
    15  	MaxDepth int
    16  
    17  	// MaxPaths specifies the maximum number of paths to explore.
    18  	// If this is 0, the number of paths is unbounded.
    19  	MaxPaths int
    20  
    21  	step, paths int
    22  }
    23  
    24  func (s *StrategyRandom) Reset() {
    25  	s.step = 0
    26  	s.paths = 0
    27  }
    28  
    29  func (s *StrategyRandom) maxDepth() int {
    30  	if s.MaxDepth == 0 {
    31  		return DefaultMaxDepth
    32  	}
    33  	return s.MaxDepth
    34  }
    35  
    36  func (s *StrategyRandom) Amb(n int) (int, bool) {
    37  	if s.step == s.maxDepth() {
    38  		return 0, false
    39  	}
    40  	s.step++
    41  	return rand.Intn(n), true
    42  }
    43  
    44  func (s *StrategyRandom) Next() bool {
    45  	s.step = 0
    46  	s.paths++
    47  	return s.MaxPaths == 0 || s.paths < s.MaxPaths
    48  }