# Reordering a list

I have a list like this:

{0,1,2,3,4,0,1,3,4,0,1,3}


This list must have a sequence of numbers from 0 to 4 repeatedly but it lacks of some numbers. How can I put the lacking numbers and hold the order of the sequences?

• What do you know, and what don't you know, about the list in the general case? If you know that you want a list repeating 0,1,2,3,4 over an over again for n times, why don't you just create this list instead of taking an incomplete list where you need to fill in the missing numbers...?
– a20
Commented May 14, 2020 at 20:15
• Along with what @a20 is asking: more context is needed here Commented May 14, 2020 at 20:27
• Module[{r = Range @@ MinMax[list]}, Flatten@Table[r, Ceiling[Length[list]/Length[r]]]] Commented May 14, 2020 at 20:36
• what happens after the ending 3? does the list stop or do we have to add 4? Commented May 14, 2020 at 20:43

Given

seq = Range[0, 4]
list = {0, 1, 2, 3, 4, 0, 1, 3, 4, 0, 1, 3}


and

fill[seq_, list_] := Flatten[seq & /@ Split[list, Less]]


then

fill[seq, list]
(* {0,1,2,3,4,0,1,2,3,4,0,1,2,3,4} *)


and also

fill[seq, {1,1,1,3,1,1}]
(* {0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4,0,1,2,3,4} *)

ls = {0, 1, 2, 3, 4, 0, 1, 3, 4, 0, 1, 3};
Table[Splice@Range[0, 4], Max[Last /@ Tally[ls]]]


{0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4}

or using SequenceReplace

ls = {0, 1, 2, 3, 4, 0, 1, 3, 4, 0, 1, 3};
If[ls[[-1]] =!= 4, ls = Join[ls, {4}]];
SequenceReplace[ls, {n0 : 0 | 1 | 2 | 3, n1_} /;n1 != n0 + 1 :> Sequence[n0, n0 + 1, n1]]


{0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4}

lst = {0, 1, 2, 3, 4, 0, 1, 3, 4, 0, 1, 3}
fun[{a_, b_}] := If[a > b, {a, b}, If[Range[a, b] == {a, b}, {a, b}, Range[a, b]]]
fun[#] & /@ Partition[lst, 2] // Flatten

lst//Table[Sequence@@Range[0,4],Length@Split[#,Less]]&

{0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4}

• In v12.1, lst//Table[Splice@Range[0,4],Length@Split[#,Less]]& Commented May 25, 2020 at 13:40

listLength = 12;

(* Out: {0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1} *)

SequenceReplace[#, {x__} /; (Less@x) :> Sequence @@ Range[0, Max@#]] & @ list

{0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4}


Is this possibly what you mean?

list = {0, 1, 2, 3, 4, 0, 1, 3, 4, 0, 1, 3};
Flatten@Join[list,
Complement[Range @@ MinMax@list, #] & /@ Split[list, Less]]

(*{0, 1, 2, 3, 4, 0, 1, 3, 4, 0, 1, 3, 2, 2, 4}*)


This seems to satisfy:

How can I put the lacking numbers and hold the order of the sequences?

list = {0, 1, 2, 3, 4, 0, 1, 3, 4, 0, 1, 3};


Using SequenceCount

c = SequenceCount[list, x_ /; Less @@ x]


3

Table[Splice @* Apply[Range] @ MinMax @ list, c]


{0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4}