What is the best way to find the period of a (repeating) list in Mathematica?

前端 未结 9 1357
没有蜡笔的小新
没有蜡笔的小新 2021-01-01 15:12

What is the best way to find the period in a repeating list?

For example:

a = {4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2}

has repeat

9条回答
  •  南方客
    南方客 (楼主)
    2021-01-01 16:11

    I propose this. It borrows from both Verbeia and Brett's answers.

    Do[
      If[MatchQ @@ Equal @@ Partition[#, i, i, 1, _], Return @@ i],
      {i, #[[ 2 ;; Floor[Length@#/2] ]] ~Position~ First@#}
    ] /. Null -> $Failed &
    

    It is not quite as efficient as Vebeia's function on long periods, but it is faster on short ones, and it is simpler as well.

提交回复
热议问题