# How can I count iterations with NestWhile?

I'd like to count loop iterations for some substitution rules.
For example:

rule = {1 -> {0}, 0 -> {1}}
init = {0}
maxIter = 10


I'm going to avoid all intermediate results, so I used NestWhile. But I need to know how many iterations happened, so I tried to use a counter and UnsameQ.

NestWhile[{#[[1]] + 1, SubstitutionSystem[rule, #[[2]]]} &, {1, init},
UnsameQ[#[[2]]] &, All, maxIter]


But this is not work. What test I should I apply to count iterations of the loop?

• I don't understand your question. What is your expected output? Commented Sep 6, 2023 at 20:09
• @lericr Some clarification added Commented Sep 7, 2023 at 7:17

I think I get it now. Let's start without the counter, and let's use NestWhileList for clarity:

NestWhileList[
SubstitutionSystem[rule, #] &,
init,
Not[MemberQ[Most[{##}], Last[{##}]]] &,
All,
maxIter]

(* {{0},{1},{0}} *)


Now let's try to add in the counter:

NestWhileList[
{#[[1]] + 1, SubstitutionSystem[rule, #[[2]]]} &,
{1, init},
Not[MemberQ[Most[{##}][[All, 2]], Last[{##}][[2]]]] &,
All,
maxIter]

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


Is that what you're looking for?

• Thank you, idea with ## helps me in a similar problem! Commented Sep 16, 2023 at 15:39