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

前端 未结 9 1201
没有蜡笔的小新
没有蜡笔的小新 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:09

    Ok, just to show my own work here:

    ModifiedTortoiseHare[a_List] := Module[{counter, tortoise, hare},
    Quiet[
     Check[
      counter = 1;
      tortoise = a[[counter]];
      hare = a[[2 counter]];
      While[(tortoise != hare) || (a[[counter ;; 2 counter - 1]] != a[[2 counter ;; 3 counter - 1]]),
       counter++;
       tortoise = a[[counter]];
       hare = a[[2 counter]];
      ];
     counter,
    $Failed]]]
    

    I'm not sure this is a 100% correct, especially with cases like {pattern,pattern,different,pattern, pattern} and it gets slower and slower when there are a lot of repeating elements, like so:

    { 1,2,1,1, 1,2,1,1, 1,2,1,1, ...} 
    

    because it is making too many expensive comparisons.

提交回复
热议问题