M
M
Mr4x2016-03-16 12:03:49
go
Mr4x, 2016-03-16 12:03:49

How to change state with different duration?

It is necessary to come up with an algorithm that switches state with different periodicity. The counter reaches a certain steps limit and switches to the next state, and then, having reached the last state, switches to the first one and starts all over again. It should work like this:

// state=1, 4 steps
update()
update()
update()
update()
// state=2, 2 steps
update()
update()
// state=3, 3 steps
update()
update()
update()
// state=1, 4 steps
update()
update()
update()
update()
// ...

This solution is not considered:
states := []int{1, 1, 1, 1, 2, 2, 3, 3, 3} // 1, 2 и 3 состояния

for i := 0; ; i++ {
    state := states[i%9]
}

Due to the overflow of the counter and the large size of the array states (in the example it is greatly reduced)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
U
uvelichitel, 2016-03-16
@Maxim_Samburskiy

Probably something like that? It works play.golang.org/p/Zo3jD2T8j8

type State struct {
  state  int
  step   int
  states []int
}
func NewState(states []int) *State {
  return &State{
    0,
    states[0],
    states,
  }
}
func (s *State) update() {
  if s.step > 0 {
    s.step--
    fmt.Println("step=", s.step) //do something
  } else {
    s.changestate()
    fmt.Println("state=", s.state) //do something else
  }
}
func (s *State) changestate() {
  if s.state < len(s.states)-1 {
    s.state++
  } else {
    s.state = 0
  }
  s.step = s.states[s.state]
}
func main() {
  st := NewState([]int{4, 2, 3, 4})
  st.update()
}

N
Nikita, 2016-03-16
@bitver

You yourself described two cycles, one (which counts the steps) inside the other (which rotates endlessly through the states).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question