Message Boards Message Boards

0
|
11825 Views
|
3 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Convert loop REPEAT to While

Posted 11 years ago
Hi, I write to ask if there is any way to convert a repeat loop that was used in modula in Mathematica a while since I've tried but if successful, here is the code in my attempt modula and conversion to Mathematica

First code in Modula-2
PROCEDURE ValAbs(x,y:CARDINAL):CARDINAL;
BEGIN
IF x>y THEN RETURN x-y ELSE RETURN y-x END;
END ValAbs;


PROCEDURE Valido(k:CARDINAL):BOOLEAN;
VAR i:CARDINAL;
BEGIN
FOR i:=1 TO k-1 DO
IF (X=X)OR (ValAbs(X,X)=ValAbs(i,k))THEN RETURN FALSE END
END;
RETURN TRUE
END Valido;

PROCEDURE Reinas(k: CARDINAL);
BEGIN
IF k>n THEN RETURN END;
X:=0;
REPEAT
INC(X);
IF Valido(k) THEN
IF  k<>n THEN  Reinas(k+1) ELSE exito:= TRUE END
END
UNTIL (X=n) OR exito;
END Reinas;

Now my translation a Mathematica
 ValAbs[x_, y_] := If[x > y, Return[x - y], Return[y - x]];
 valido[k_] := Module[{i}, For[i = 1, i < k - 1, i++,
    If[
     Or[
      x[[i]] == x[[k]], ValAbs[x[[i]], x[[k]]] == ValAbs[i, k]],
     Return[False]
     ]
    ];
   Return[True]
  ];

Reinas[k_] := Module[{}, If[k > n, Return["error"]];
  x[[k]] = 0;
  While[ x[[k]] !=  n && Not[exito],
   x[[k]]++;
   If[valido[k],
    If[k != n, Reinas[k + 1], exito = True]]]]

n = 5;
x = Table[0, {n}]
exito = False;

Reinas[1]
x

The value de x es {1,1,2,2,3} when it should be other.
POSTED BY: Luis Ledesma
3 Replies
If you want the For loop in the valido function to run for i = 1, ..., k - 1, it should be something like
For[i = 1, i < k, i++, ...
or
For[i = 1, i <= k - 1, i++, ...
then it does indeed return {1, 3, 5, 2, 4}.
POSTED BY: Ilian Gachevski
Posted 11 years ago
In the past posting a picture of the source code was a bad idea because the reader needed to type it all back in to test a solution, but with the new forum source code with special characters is often corrupted and this makes it very difficult to guess what the original source was.

If you can provide a clear picture of the page with the complete Modula code or there is a URL clearly showing that code, I searched and didn't find one, then your question should be easy to answer.
POSTED BY: Bill Simpson
Posted 11 years ago
The value of x in fact x={1,3,,5,2,4}
since I've consulted MODULA-2 output
POSTED BY: Luis Ledesma
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