Message Boards Message Boards

0
|
3676 Views
|
2 Replies
|
1 Total Likes
View groups...
Share
Share this post:

Avoid error with the following recursive code?

Posted 5 years ago

Thanks for any help! I must be doing something wrong in the following recursive code:

ClearAll[lim, hlim, count, e]
lim = 25;
hlim = lim/5;
count[heading_, v_] := count[heading, v] = Block[{nv = v},
   If[Total[nv] == lim,
    If[heading == 0, 1, 0],
    If[nv[[heading]] == hlim, 0,
     nv[[heading]] = nv[[heading]] + 1;
     count[If[heading == 4, 0, heading + 1], nv] + 
      count[If[heading == 0, 4, heading - 1], nv]]]]
e[] := Module[{}, 2*count[1, {1, 0, 0, 0, 0}]]
e[] // Timing

I expect a number, but I get:

{0.007164, 
 870 If[List == 5, 0, nv[[0]] = nv[[0]] + 1; 
   count[If[0 == 4, 0, 0 + 1], nv] + count[If[0 == 0, 4, 0 - 1], nv]]}
POSTED BY: Joe Gilray
2 Replies
Posted 5 years ago

Thanks Gianluca! Of course, I meant to index v from 1 to 5 not 0 to 4. Comes from spending the past 2 months programming in Racket and Rust... how quickly I forget. :-/

POSTED BY: Joe Gilray

When the variable heading becomes zero, the test nv[[heading]] == hlim becomes List==5, which may not be what you intended.

POSTED BY: Gianluca Gorni
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract