4-rings or 4-squares puzzle: Difference between revisions

m
Line 712:
</pre>
=={{header|Fortran}}==
This uses the facility standardised in F90 whereby DO-loops can have text labels attached (not in the usual label area) so that the END DO statement can have the corresponding label, and any CYCLE statements can use it also. Similarly, the subroutine's END statement bears the name of the subroutine. This is just syntactic decoration. Rather more useful is extended syntax for dealing with arrays and especially the function ALL for making multiple tests without having to enumerate them in the code. To gain this convenience, the EQUIVALENCE statement makes variables A, B, C, D, E, F, and G occupy the same storage as <code>INTEGER IV(7)</code>, an array.
 
One could abandon the use of the named variables in favour of manipulating the array equivalent, and indeed develop code which performs the nested loops via messing with the array, but for simplicity, the individual variables are used. However, tempting though it is to write a systematic sequence of seven nested DO-loops, the variables are not in fact all independent: some are fixed once others are chosen. Just cycling through all the notional possibilities when one only is in fact possible is a bit too much brute-force-and-ignorance, though other problems with other constraints, may encourage such exhaustive stepping. As a result, the code is more tightly bound to the specific features of the problem.
Line 723:
LOGICAL UNIQUE !Solutions need not have unique values.
INTEGER A,B,C,D,E,F,G !Ah, Diophantus of Alexandria.
INTEGER IV(7),S,N !Assistants.
EQUIVALENCE (IV(1),A),(IV(2),B),(IV(3),C), !Yes,
1 (IV(4),D),(IV(5),E),(IV(6),F),(IV(7),G) !We're all individuals.
WRITE (6,1) FIRST,LAST
1 FORMAT (/,"The Four Rings puzzle, over ",I0," to ",I0,".",$) !An addendum follows.
Line 736:
IF (UNIQUE .AND. B.EQ.C) CYCLE CC !The first constraint shows up.
DD:DO D = FIRST,LAST !Start by forming B, C, and D.
IF (UNIQUE .AND. ANY(IV(2:3).EQ.D)) CYCLE DD !Ignoring A just for now.
S = B + C + D !This is the common sum.
A = S - B !The value of A is not free from BCD.
IF (A < FIRST .OR. A > LAST) CYCLE DD !And it may not be within bounds.
IF (UNIQUE .AND. ANY(IV(2:4).EQ.A)) CYCLE DD !Or, if required so, unique.
EE:DO E = FIRST,LAST !Righto, A,B,C,D are valid. Try an E.
IF (UNIQUE .AND. ANY(IV(1:4).EQ.E)) CYCLE EE !Precluded already?
F = S - (E + D) !No. So therefore, F is determined.
IF (F < FIRST .OR. F > LAST) CYCLE EE !Acceptable?
IF (UNIQUE .AND. ANY(IV(1:5).EQ.F)) CYCLE EE !And, if required, unique?
G = S - F !Yes! So finally, G is determined.
IF (G < FIRST .OR. G > LAST) CYCLE EE !Acceptable?
IF (UNIQUE .AND. ANY(IV(1:6).EQ.G)) CYCLE EE !And, if required, unique?
N = N + 1 !Yes! Count a solution set!
IF (UNIQUE) WRITE (6,"(7I3)") IV !Show its values.
END DO EE !Consder another E.
END DO DD !Consider another D.
1,220

edits