2
$\begingroup$

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?

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

1 Answer 1

5
$\begingroup$

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?

$\endgroup$
1
  • $\begingroup$ Thank you, idea with ## helps me in a similar problem! $\endgroup$
    – lesobrod
    Commented Sep 16, 2023 at 15:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.