Department numbers: Difference between revisions
m
→{{header|ABC}}: Trans
(→{{header|Minimal BASIC}}: Added) |
m (→{{header|ABC}}: Trans) |
||
(44 intermediate revisions by 20 users not shown) | |||
Line 28:
=={{header|11l}}==
{{trans|C}}
<
print(‘----------------------------------’)
Line 35:
L(fire) 1..7
I police!=sanitation & sanitation!=fire & fire!=police & police+fire+sanitation==12
print(police"\t\t"sanitation"\t\t"fire)</
{{Output}}
<pre>
Line 57:
=={{header|8080 Assembly}}==
<
lxi h,obuf ; HL = output buffer
mvi b,2 ; B = police
Line 105:
ret
ohdr: db 'P S F',13,10
obuf: equ $ ; Output buffer goes after program</
{{out}}
Line 128:
=={{header|8086 Assembly}}==
<
bits 16
org 100h
Line 177:
section .data
ohdr: db 'P S F',13,10 ; Header
obuf: equ $ ; Place to write output</
{{out}}
Line 198:
</pre>
=={{header|ABC}}==
{{Trans|ALGOL 68}}
<syntaxhighlight lang="abc">
PUT 7 IN max.department.number
PUT 12 IN department.sum
WRITE "police sanitation fire" /
PUT 2 IN police
WHILE police <= max.department.number:
FOR sanitation IN { 1 .. max.department.number }:
IF sanitation <> police:
PUT ( department.sum - police ) - sanitation IN fire
IF fire > 0 AND fire <= max.department.number AND fire <> sanitation AND fire <> police:
WRITE police>>6, sanitation>>11, fire>>5 /
PUT police + 2 IN police</syntaxhighlight>
{{out}}
<pre>
police sanitation fire
2 3 7
2 4 6
2 6 4
2 7 3
4 1 7
4 2 6
4 3 5
4 5 3
4 6 2
4 7 1
6 1 5
6 2 4
6 4 2
6 5 1
</pre>
=={{header|Action!}}==
<
BYTE p,s,f
Line 216 ⟶ 249:
OD
OD
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Department_numbers.png Screenshot from Atari 8-bit computer]
Line 238 ⟶ 271:
=={{header|Ada}}==
<
procedure Department_Numbers is
Line 259 ⟶ 292:
end loop;
end loop;
end Department_Numbers;</
{{out}}
Line 281 ⟶ 314:
=={{header|Aime}}==
<
p = 0;
Line 294 ⟶ 327:
}
}
}</
=={{header|ALGOL 68}}==
As noted in the Fortran sample, once the police and sanitation departments are posited, the fire department value is fixed
<
# show possible department number allocations for police, sanitation and fire departments #
# the police department number must be even, all department numbers in the range 1 .. 7 #
Line 323 ⟶ 356:
OD
OD
END</
{{out}}
<pre>
Line 345 ⟶ 378:
=={{header|ALGOL W}}==
{{Trans|ALGOL 68}}
<
% show possible department number allocations for police, sanitation and fire departments %
% the police department number must be even, all department numbers in the range 1 .. 7 %
Line 364 ⟶ 397:
end for_sanitation
end for_police
end.</
{{out}}
<pre>
Line 386 ⟶ 419:
=={{header|APL}}==
<
This prints each triplet of numbers from 1 to 7 for which:
Line 415 ⟶ 448:
Briefly, composing a solution from generic functions:
<
script
on |λ|(x)
Line 479 ⟶ 512:
on unlines(xs)
intercalate(linefeed, xs)
end unlines</
{{Out}}
<pre>237
Line 499 ⟶ 532:
{{Trans|JavaScript}}
{{Trans|Haskell}}
<
-- options :: Int -> Int -> Int -> [(Int, Int, Int)]
Line 672 ⟶ 705:
on unlines(xs)
intercalate(linefeed, xs)
end unlines</
{{Out}}
<pre>(Police, Sanitation, Fire)
Line 695 ⟶ 728:
=={{header|Arturo}}==
<
loop 1..7 'y [
loop 1..7 'z [
Line 705 ⟶ 738:
]
]
]</
{{out}}
Line 723 ⟶ 756:
6 4 2
6 5 1</pre>
=={{header|Asymptote}}==
<syntaxhighlight lang="asymptote">write("--police-- --sanitation-- --fire--");
for(int police = 2; police < 6; police += 2) {
for(int sanitation = 1; sanitation < 7; ++sanitation) {
for(int fire = 1; fire < 7; ++fire) {
if(police != sanitation && sanitation != fire && fire != police && police+fire+sanitation == 12){
write(" ", police, suffix=none);
write(" ", sanitation, suffix=none);
write(" ", fire);
}
}
}
}</syntaxhighlight>
=={{header|AutoHotkey}}==
<
res := IsObject(res) ? res : [], dup := IsObject(dup) ? dup : []
if (n > j)
Line 740 ⟶ 788:
Sort, res, D`n
return StrReplace(res, "`n", Delim)
}</
Example:<
for k, v in perm(elements, n)
if (SubStr(v, 1, 1) + SubStr(v, 2, 1) + SubStr(v, 3, 1) = 12) && (SubStr(v, 1, 1) / 2 = Floor(SubStr(v, 1, 1)/2))
Line 747 ⟶ 795:
MsgBox, 262144, , % res4
return</
Outputs:<pre>237
246
Line 764 ⟶ 812:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f DEPARTMENT_NUMBERS.AWK
BEGIN {
Line 785 ⟶ 833:
return(stmt1 stmt2 stmt3)
}
</syntaxhighlight>
{{out}}
<pre>
Line 806 ⟶ 854:
=={{header|BCPL}}==
<
let start() be
Line 813 ⟶ 861:
for f=1 to 7
if p~=s & s~=f & p~=f & p+s+f=12 then
writef("%N %N %N*N", p, s, f)</
{{out}}
<pre>2 3 7
Line 829 ⟶ 877:
6 4 2
6 5 1</pre>
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
The [[#Sinclair_ZX81_BASIC|Sinclair ZX81 BASIC]] solution works without any changes.
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">print "--police-- --sanitation-- --fire--"
for police = 2 to 7 step 2
for fire = 1 to 7
if fire = police then continue for
sanitation = 12 - police - fire
if sanitation = fire or sanitation = police then continue for
if sanitation >= 1 and sanitation <= 7 then
print rjust(police, 6); rjust(fire, 13); rjust(sanitation, 12)
end if
next fire
next police</syntaxhighlight>
{{out}}
<pre>--police-- --sanitation-- --fire--
2 3 7
2 4 6
2 6 4
2 7 3
4 1 7
4 2 6
4 3 5
4 5 3
4 6 2
4 7 1
6 1 5
6 2 4
6 4 2
6 5 1</pre>
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="qbasic">10 CLS
20 PRINT "--police-- --sanitation-- --fire--"
30 FOR police = 2 TO 7 STEP 2
40 FOR fire = 1 TO 7
50 sanitation = 12-police-fire
60 IF sanitation >= 1 AND sanitation <= 7 THEN
70 PRINT TAB (5)police TAB (18)fire TAB (30)sanitation
80 endif
90 NEXT fire
100 NEXT police</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
==={{header|Craft Basic}}===
<syntaxhighlight lang="basic">print "P S F"
for p = 2 to 7 step 2
for s = 1 to 7
if s <> p then
let f = (12 - p) - s
if f > 0 and f <= 7 and f <> s and f <> p then
print p, " ", s, " ", f
endif
endif
next s
next p
end</syntaxhighlight>
{{out| Output}}<pre>P S F
2 3 7
2 4 6
2 6 4
2 7 3
4 1 7
4 2 6
4 3 5
4 5 3
4 6 2
4 7 1
6 1 5
6 2 4
6 4 2
6 5 1</pre>
==={{header|Run BASIC}}===
<syntaxhighlight lang="runbasic">print "police fire sanitation"
for police = 2 to 7 step 2
for fire = 1 to 7
if fire = police then [cont]
sanitation = (12-police)-fire
if sanitation <= 0 or sanitation > 7 or sanitation = fire or sanitation = police then [cont]
print " "; police; chr$(9); fire; chr$(9); sanitation
[cont]
next fire
next police</syntaxhighlight>
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">OpenConsole()
PrintN("--police-- --sanitation-- --fire--")
For police = 2 To 7 Step 2
For fire = 1 To 7
If fire = police:
Continue
EndIf
sanitation = 12 - police - fire
If sanitation = fire Or sanitation = police: Continue : EndIf
If sanitation >= 1 And sanitation <= 7:
PrintN(" " + Str(police) + #TAB$ + #TAB$ + Str(fire) + #TAB$ + #TAB$ + Str(sanitation))
EndIf
Next fire
Next police
Input()
CloseConsole()</syntaxhighlight>
{{out}}
<pre>Same as BASIC256 entry.</pre>
==={{header|Yabasic}}===
<syntaxhighlight lang="freebasic">print "--police-- --sanitation-- --fire--"
for police = 2 to 7 step 2
for fire = 1 to 7
if fire = police continue
sanitation = 12 - police - fire
if sanitation = fire or sanitation = police continue
if sanitation >= 1 and sanitation <= 7 print police using "######", fire using "############", sanitation using "###########"
next fire
next police</syntaxhighlight>
{{out}}
<pre>Same as BASIC256 entry.</pre>
==={{header|IS-BASIC}}===
<
110 FOR P=2 TO 7 STEP 2
120 FOR S=1 TO 7
Line 839 ⟶ 1,025:
141 END IF
150 NEXT
160 NEXT</
==={{header|Minimal BASIC}}===
{{trans|Sinclair ZX81 BASIC}}
<syntaxhighlight lang="basic">
10 REM Department numbers
20 PRINT "POLICE SANITATION FIRE"
30 FOR P = 2 TO 7 STEP 2
40 FOR S = 1 TO 7
50 IF S = P THEN
60 LET F = (12-P)-S
70 IF F <= 0
80 IF F > 7 THEN 120
90
100
110 PRINT TAB(3); P; TAB(11); S; TAB(19); F
120 NEXT S
130 NEXT P
140 END
</syntaxhighlight>
==={{header|Quite BASIC}}===
{{trans|Sinclair ZX81 BASIC}}
<syntaxhighlight lang="basic">
10 REM Department numbers
20 PRINT "POLICE SANITATION FIRE"
30 FOR P = 2 TO 7 STEP 2
40 FOR S = 1 TO 7
50 IF S = P THEN 80
60 LET F = (12-P)-S
70 IF F > 0 AND F <= 7 AND F <> S AND F <> P THEN PRINT " ";P;" ";S;" ";F
80 NEXT S
90 NEXT P
100 END
</syntaxhighlight>
{{out}}
<pre>
POLICE SANITATION FIRE
2 3 7
2 4 6
2 6 4
2 7 3
4 1 7
4 2 6
4 3 5
4 5 3
4 6 2
4 7 1
6 1 5
6 2 4
6 4 2
6 5 1
</pre>
==={{header|Sinclair ZX81 BASIC}}===
Works with 1k of RAM. This program ought not to need more than minimal changes to be compatible with any old-style BASIC dialect.
<
20 FOR P=2 TO 7 STEP 2
30 FOR S=1 TO 7
Line 866 ⟶ 1,088:
60 IF F>0 AND F<=7 AND F<>S AND F<>P THEN PRINT " ";P;" ";S;" ";F
70 NEXT S
80 NEXT P</
{{out}}
<pre>POLICE SANITATION FIRE
Line 886 ⟶ 1,108:
==={{header|BBC BASIC}}===
{{trans|ALGOL 68}}
<
max_dept_num% = 7
dept_sum% = 12
Line 898 ⟶ 1,120:
NEXT
NEXT
END</
{{out}}
<pre>police sanitation fire
Line 915 ⟶ 1,137:
6 4 2
6 5 1</pre>
==={{header|QBasic}}===
<syntaxhighlight lang="qbasic">PRINT "--police-- --sanitation-- --fire--"
FOR police = 2 TO 7 STEP 2
FOR fire = 1 TO 7
IF fire = police THEN GOTO cont
sanitation = 12 - police - fire
IF sanitation = fire OR sanitation = police THEN GOTO cont
IF sanitation >= 1 AND sanitation <= 7 THEN
PRINT USING " # # #"; police; fire; sanitation
END IF
cont:
NEXT fire
NEXT police</syntaxhighlight>
==={{header|XBasic}}===
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">PROGRAM "Depar/num"
DECLARE FUNCTION Entry ()
FUNCTION Entry ()
PRINT "police sanitation fire"
FOR police = 2 TO 7 STEP 2
FOR fire = 1 TO 7
IF fire = police THEN GOTO cont
sanitation = 12 - police - fire
IF sanitation = fire OR sanitation = police THEN GOTO cont
IF sanitation >= 1 AND sanitation <= 7 THEN
PRINT TAB(3); police; TAB(13); fire; TAB(22); sanitation
END IF
cont:
NEXT fire
NEXT police
END FUNCTION
END PROGRAM </syntaxhighlight>
=={{header|C}}==
Weird that such a simple task was still not implemented in C, would be great to see some really creative ( obfuscated ) solutions for this one.
<syntaxhighlight lang="c">
#include<stdio.h>
Line 940 ⟶ 1,200:
return 0;
}
</syntaxhighlight>
Output:
<pre>
Line 962 ⟶ 1,222:
=={{header|C sharp|C#}}==
<
public class Program
{
Line 977 ⟶ 1,237:
}
}
}</
{{out}}
<pre>
Line 997 ⟶ 1,257:
=={{header|C++}}==
<
#include <iostream>
#include <iomanip>
Line 1,016 ⟶ 1,276:
}
return 0;
}</
{{out}}
<pre>
Line 1,037 ⟶ 1,297:
=={{header|Clojure}}==
<
(for [police n
sanitation n
Line 1,044 ⟶ 1,304:
:when (even? police)
:when (= 12 (+ police sanitation fire))]
(println police sanitation fire)))</
{{Out}}
<pre>
Line 1,064 ⟶ 1,324:
=={{header|CLU}}==
<
po: stream := stream$primary_output()
Line 1,083 ⟶ 1,343:
end
end
end start_up</
{{out}}
<pre>P S F
Line 1,101 ⟶ 1,361:
6 4 2
6 5 1</pre>
=={{header|COBOL}}==
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. DEPARTMENT-NUMBERS.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 BANNER PIC X(24) VALUE "POLICE SANITATION FIRE".
01 COMBINATION.
03 FILLER PIC X(5) VALUE SPACES.
03 POLICE PIC 9.
03 FILLER PIC X(11) VALUE SPACES.
03 SANITATION PIC 9.
03 FILLER PIC X(5) VALUE SPACES.
03 FIRE PIC 9.
01 TOTAL PIC 99.
PROCEDURE DIVISION.
BEGIN.
DISPLAY BANNER.
PERFORM POLICE-LOOP VARYING POLICE FROM 2 BY 2
UNTIL POLICE IS GREATER THAN 6.
STOP RUN.
POLICE-LOOP.
PERFORM SANITATION-LOOP VARYING SANITATION FROM 1 BY 1
UNTIL SANITATION IS GREATER THAN 7.
SANITATION-LOOP.
PERFORM FIRE-LOOP VARYING FIRE FROM 1 BY 1
UNTIL FIRE IS GREATER THAN 7.
FIRE-LOOP.
ADD POLICE, SANITATION, FIRE GIVING TOTAL.
IF POLICE IS NOT EQUAL TO SANITATION
AND POLICE IS NOT EQUAL TO FIRE
AND SANITATION IS NOT EQUAL TO FIRE
AND TOTAL IS EQUAL TO 12,
DISPLAY COMBINATION.</syntaxhighlight>
{{out}}
<pre>POLICE SANITATION FIRE
2 3 7
2 4 6
2 6 4
2 7 3
4 1 7
4 2 6
4 3 5
4 5 3
4 6 2
4 7 1
6 1 5
6 2 4
6 4 2
6 5 1</pre>
=={{header|Cowgol}}==
<
typedef Dpt is int(1, 7);
Line 1,132 ⟶ 1,447:
end loop;
pol := pol + 2;
end loop;</
{{out}}
Line 1,155 ⟶ 1,470:
{{Trans|C++}}
<syntaxhighlight lang="d">
import std.stdio, std.range;
Line 1,171 ⟶ 1,486:
}
}
</syntaxhighlight>
Output:
<pre>
Line 1,193 ⟶ 1,508:
{{libheader| System.SysUtils}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
program Department_numbers;
Line 1,229 ⟶ 1,544:
writeln(#10, count, ' valid combinations');
readln;
end.</
=={{header|Draco}}==
<syntaxhighlight lang="draco">proc main() void:
byte police, sanitation, fire;
writeln("Police Sanitation Fire");
for police from 2 by 2 upto 7 do
for sanitation from 1 upto 7 do
for fire from 1 upto 7 do
if police /= sanitation
and police /= fire
and sanitation /= fire
and police + sanitation + fire = 12 then
writeln(police:6, " ", sanitation:10, " ", fire:4)
fi
od
od
od
corp</syntaxhighlight>
{{out}}
<pre>Police Sanitation Fire
2 3 7
2 4 6
2 6 4
2 7 3
4 1 7
4 2 6
4 3 5
4 5 3
4 6 2
4 7 1
6 1 5
6 2 4
6 4 2
6 5 1</pre>
=={{header|EasyLang}}==
{{trans|C}}
<syntaxhighlight lang="easylang">
numfmt 0 3
for pol = 2 step 2 to 6
for san = 1 to 7
for fire = 1 to 7
if pol <> san and san <> fire and fire <> pol
if pol + fire + san = 12
print pol & san & fire
.
.
.
.
.
</syntaxhighlight>
=={{header|Elixir}}==
<
IO.puts("P - F - S")
for p <- [2,4,6],
Line 1,242 ⟶ 1,609:
|> Enum.each(&IO.puts/1)
</syntaxhighlight>
<
P - F - S
2 - 3 - 7
Line 1,259 ⟶ 1,626:
6 - 4 - 2
6 - 5 - 1
</syntaxhighlight>
=={{header|Excel}}==
Line 1,269 ⟶ 1,636:
{{Works with|Office 365 betas 2021}}
<
=validRows(
LAMBDA(ab,
Line 1,293 ⟶ 1,660:
)
)
)</
and also assuming the following generic bindings in the Name Manager for the WorkBook:
<
=LAMBDA(xs,
LAMBDA(ys,
Line 1,339 ⟶ 1,706:
)
)
)</
{{Out}}
Line 1,443 ⟶ 1,810:
=={{header|F_Sharp|F#}}==
<
// A function to generate department numbers. Nigel Galloway: May 2nd., 2018
type dNum = {Police:int; Fire:int; Sanitation:int}
let fN n=n.Police%2=0&&n.Police+n.Fire+n.Sanitation=12&&n.Police<>n.Fire&&n.Police<>n.Sanitation&&n.Fire<>n.Sanitation
List.init (7*7*7) (fun n->{Police=n%7+1;Fire=(n/7)%7+1;Sanitation=(n/49)+1})|>List.filter fN|>List.iter(printfn "%A")
</syntaxhighlight>
{{out}}
<pre>
Line 1,496 ⟶ 1,863:
=={{header|Factor}}==
<
sequences sets ;
IN: rosetta-code.department-numbers
Line 1,504 ⟶ 1,871:
"{ Police, Sanitation, Fire }" print nl
[ "%[%d, %]\n" printf ] each</
{{out}}
<pre>
Line 1,525 ⟶ 1,892:
</pre>
=={{header|Fermat}}==
<
!!'------|----------|----';
for p = 2 to 6 by 2 do
Line 1,531 ⟶ 1,898:
for f = 1 to 7 do
if p+f+s=12 and f<>p and f<>s and s<>p then !!(' ',p,' ',s,' ',f);
fi od od od;</
{{out}}<pre>
Police Sanitation Fire
Line 1,552 ⟶ 1,919:
=={{header|FOCAL}}==
<
01.20 Q
Line 1,560 ⟶ 1,927:
02.40 I (P+S+G-12)2.6,2.5,2.6
02.50 T %1,P,S,G,!
02.60 R</
{{out}}
<pre>= 2= 3= 7
Line 1,578 ⟶ 1,945:
=={{header|Forth}}==
<
: fire ( pol san fir -- )
2dup = if 2drop drop exit then
Line 1,600 ⟶ 1,967:
\ tries to assign numbers with police = 2, 4, or 6
: departments cr \ leave input line
8 2 do i police 2 +loop ;</
{{out}}
Line 1,629 ⟶ 1,996:
Since the modernisers of Fortran made a point of specifying that it does not specify the manner of evaluation of compound boolean expressions, specifically, that there is to be no reliance on [[Short-circuit_evaluation]], both parts of the compound expression of the line labelled 5 "may" be evaluated even though the first may have determined the result. Prior to the introduction of LOGICAL variables with F66, one employed integer arithmetic as is demonstrated in the arithmetic-IF test of the line labelled 6. On the B6700, this usage ran faster than the corresponding boolean expression - possibly because there was no test for short-circuiting the expression when the first part of a multiply was zero...
Note that the syntax enables ''two'' classes of labels: the old-style numerical label in columns one to five, and the special label-like prefix of a DO-loop that is not in columns one to five. And yes, a line can have both. <
1 PP:DO P = 2,7,2 !The police demand an even number. They're special and use violence.
2 SS:DO S = 1,7 !The sanitation department accepts any value.
Line 1,639 ⟶ 2,006:
8 END DO SS !Next S
9 END DO PP !Next P.
END !Well, that was straightforward.</
Output:
<pre>
Line 1,659 ⟶ 2,026:
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
Line 1,682 ⟶ 2,049:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>police fire sanitation
Line 1,700 ⟶ 2,067:
6 4 2
6 5 1 </pre>
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
void local fn DepartmentNumbers
long police, sanitation, fire
printf @"Police Sanitation Fire"
printf @"-------------------------------"
for police = 2 to 7 step 2
for fire = 1 to 7
if ( fire = police ) then continue
sanitation = 12 - police - fire
if ( sanitation == fire ) or ( sanitation == police ) then continue
if ( sanitation >= 1 ) and ( sanitation <= 7 )
printf @"%4d%12d%13d", police, fire, sanitation
end if
next
next
end fn
window 1
fn DepartmentNumbers
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Police Sanitation Fire
-------------------------------
2 3 7
2 4 6
2 6 4
2 7 3
4 1 7
4 2 6
4 3 5
4 5 3
4 6 2
4 7 1
6 1 5
6 2 4
6 4 2
6 5 1
</pre>
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=cdfeadc26aaeb0e23f4523626b6fe7c9 Click this link to run this code]'''
<
Dim siC0, siC1, siC2 As Short
Dim sOut As New String[]
Line 1,726 ⟶ 2,145:
Next
End</
Output:
<pre>
Line 1,748 ⟶ 2,167:
=={{header|Go}}==
{{trans|Kotlin}}
<
import "fmt"
Line 1,768 ⟶ 2,187:
}
fmt.Printf("\n%d valid combinations\n", count)
}</
{{out}}
Line 1,794 ⟶ 2,213:
=={{header|Groovy}}==
{{trans|Java}}
<
static void main(String[] args) {
println("Police Sanitation Fire")
Line 1,813 ⟶ 2,232:
println("$count valid combinations")
}
}</
{{out}}
<pre>Police Sanitation Fire
Line 1,835 ⟶ 2,254:
=={{header|GW-BASIC}}==
<
20 PRINT "------|----------|----"
30 FOR P = 2 TO 7 STEP 2
Line 1,845 ⟶ 2,264:
90 NEXT F
100 NEXT S
110 NEXT P</
=={{header|Haskell}}==
Bare minimum:
<
main =
mapM_ print $
Line 1,860 ⟶ 2,279:
case y /= z && 1 <= z && z <= 7 of
True -> [(x, y, z)]
_ -> []</
or, resugaring this into list comprehension format:
<
main =
mapM_
Line 1,870 ⟶ 2,289:
, y <- [1 .. 7]
, z <- [12 - (x + y)]
, y /= z && 1 <= z && z <= 7 ]</
Do notation:
<
main =
mapM_ print $
Line 1,880 ⟶ 2,299:
if y /= z && 1 <= z && z <= 7
then [(x, y, z)]
else []</
Unadorned brute force – more than enough at this small scale:
<
main :: IO ()
Line 1,895 ⟶ 2,314:
\z ->
[ (x, y, z)
| even x && 3 == length (nub [x, y, z]) && 12 == sum [x, y, z] ]</
{{Out}}
<pre>(2,3,7)
Line 1,913 ⟶ 2,332:
Or, more generally:
<syntaxhighlight lang="haskell">-------------------- DEPARTMENT NUMBERS ------------------
options :: Int -> Int -> Int -> [(Int, Int, Int)]
options lo hi total =
( \ds ->
filter even ds
>>= \x ->
filter (/= x) ds
>>= \y ->
[total - (x + y)]
>>= \z ->
)
[lo .. hi]
main :: IO ()
main =
let xs = options 1 7 12
in putStrLn "(Police, Sanitation, Fire)\n"
>> mapM_ print xs
>> mapM_
putStrLn
[ "\nNumber of options: ",
show (length xs)
]</syntaxhighlight>
Reaching again for a little more syntactic sugar, the options function above could also be re-written either as a list comprehension,
<
options lo hi total =
let ds = [lo .. hi]
Line 1,943 ⟶ 2,369:
, y <- filter (/= x) ds
, let z = total - (x + y)
, y /= z && lo <= z && z <= hi ]</
or in Do notation:
<
options :: Int -> Int -> Int -> [(Int, Int, Int)]
Line 1,955 ⟶ 2,381:
let z = total - (x + y)
guard $ y /= z && lo <= z && z <= hi
return (x, y, z)</
{{Out}}
<pre>(Police, Sanitation, Fire)
Line 1,979 ⟶ 2,405:
=={{header|J}}==
'''Solution:'''
<
permfrom=: ,/@(perm@[ {"_ 1 comb) NB. get permutations of length x from y possible items
Line 1,990 ⟶ 2,416:
Validnums=: >: i.7 NB. valid Department numbers
getDeptNums=: [: (#~ conditions"1) Validnums {~ permfrom</
'''Example usage:'''
<
4 1 7
4 7 1
Line 2,006 ⟶ 2,432:
6 4 2
4 3 5
4 5 3</
===Alternate
<
4 1 7
6 1 5
2 3 7
2 4 6
4 3 5</
Note that we are only showing the distinct valid [[combinations]] here, not all valid [[permutations]] of those combinations. (Valid permutations would be: swapping the last two values in a combination, and all permutations of 2 4 6.)
Another variation would be more constraint based, blindly implementing the rules of the task and yielding all valid permutations. (Shown here with the number of possibilities at each step):
<syntaxhighlight lang=J> NB. 3 departments, 1..7 in each
#rule1=. >,{3#<1+i.7
343
NB. total must be 12, numbers must be unique
#rule2=. (#~ ((3=#@~.) * 12=+/)"1) rule1
30
NB. no odd numbers in police department (first department)
#rule3=. (#~ 0=2|{."1) rule2
14
rule3
2 3 7
2 4 6
2 6 4
2 7 3
4 1 7
4 2 6
4 3 5
4 5 3
4 6 2
4 7 1
6 1 5
6 2 4
6 4 2
6 5 1</syntaxhighlight>
=={{header|Java}}==
{{trans|Kotlin}}
<
public static void main(String[] args) {
System.out.println("Police Sanitation Fire");
Line 2,039 ⟶ 2,492:
System.out.printf("\n%d valid combinations", count);
}
}</
{{out}}
<pre>Police Sanitation Fire
Line 2,061 ⟶ 2,514:
===ES5===
Briefly:
<
'use strict';
Line 2,081 ⟶ 2,534:
.map(JSON.stringify)
.join('\n');
})();</
{{Out}}
<pre>(Police, Sanitation, Fire)
Line 2,101 ⟶ 2,554:
Or, more generally:
{{Trans|Haskell}}
<
'use strict';
Line 2,179 ⟶ 2,632:
return '(Police, Sanitation, Fire)\n\n' +
unlines(map(show, xs)) + '\n\nNumber of options: ' + length(xs);
})();</
{{Out}}
<pre>(Police, Sanitation, Fire)
Line 2,202 ⟶ 2,655:
===ES6===
Briefly:
<
"use strict";
const
label = "(Police, Sanitation, Fire)",
solutions = [2, 4, 6]
.flatMap(
z => z !== y && 1 <= z && z <= 7 ? [
[x, y, z]
] : [
)
)
)
.map(JSON.stringify)
.join(
return `${label}\n${solutions}`;
})();</syntaxhighlight>
{{Out}}
<pre>(Police, Sanitation, Fire)
Line 2,239 ⟶ 2,696:
Or, more generally, by composition of generic functions:
{{Trans|Haskell}}
<
//
// options :: Int -> Int -> Int -> [(Int, Int, Int)]
const options =
const
bind =
ds = enumFromTo(lo
return bind(ds.filter(even
x => bind(ds.filter(d => d !== x
y => bind([total - (x + y)]
z => (z !== y && lo <= z && z <= hi) ? [
[x, y, z]
Line 2,258 ⟶ 2,715:
)
)
);
};
//
const main = () => {
const
label = "(Police, Sanitation, Fire)",
solutions = options(1)(7)(12),
n = solutions.length,
list = solutions
.map(JSON.stringify)
.join("\n");
return (
`${label}\n\n${list}\n\nNumber of options: ${n}`
);
};
// ---------------- GENERIC FUNCTIONS ----------------
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo =
n => Array.from({
length:
}, (_, i) => m + i);
Line 2,275 ⟶ 2,744:
const even = n => n % 2 === 0;
//
return main();
})();</syntaxhighlight>
{{Out}}
<pre>(Police, Sanitation, Fire)
Line 2,335 ⟶ 2,783:
'''Nested for-loop'''
<
(fire != police) and (fire != sanitation) and (police != sanitation)
and (fire + police + sanitation == 12)
Line 2,344 ⟶ 2,792:
| range(1;8) as $sanitation
| select( check($fire; $police; $sanitation) )
| {$fire, $police, $sanitation}</
'''In Brief'''
<
| select( .fire != .police and .fire != .sanitation and .police != .sanitation
and .fire + .police + .sanitation == 12
and .police % 2 == 0 )</
'''combinations'''
<syntaxhighlight lang="jq">
[range(1;8)]
| combinations(3)
| select( add == 12 and .[1] % 2 == 0)
| {fire: .[0], police: .[1], sanitation: .[2]}</
=={{header|Julia}}==
<
function findsolution(rng=1:7)
Line 2,381 ⟶ 2,829:
printsolutions(findsolution())
</syntaxhighlight>
{{out}}
Line 2,402 ⟶ 2,850:
=={{header|Kotlin}}==
<
fun main(args: Array<String>) {
Line 2,420 ⟶ 2,868:
}
println("\n$count valid combinations")
}</
{{out}}
Line 2,445 ⟶ 2,893:
=={{header|Lua}}==
<
print( "Fire", "Police", "Sanitation" )
sol = 0
Line 2,458 ⟶ 2,906:
end
print( string.format( "\n%d solutions found", sol ) )
</syntaxhighlight>
{{out}}
<pre>
Line 2,479 ⟶ 2,927:
14 solutions found
</pre>
=={{header|MAD}}==
<syntaxhighlight lang="mad"> NORMAL MODE IS INTEGER
PRINT COMMENT $ POLICE SANITATION FIRE$
THROUGH LOOP, FOR P=2, 2, P.G.7
THROUGH LOOP, FOR S=1, 1, S.G.7
THROUGH LOOP, FOR F=1, 1, F.G.7
WHENEVER P.E.S .OR. P.E.F .OR. S.E.F, TRANSFER TO LOOP
WHENEVER P+S+F .E. 12, PRINT FORMAT OCC, P, S, F
LOOP CONTINUE
VECTOR VALUES OCC = $I6,S2,I10,S2,I4*$
END OF PROGRAM</syntaxhighlight>
{{out}}
<pre>POLICE SANITATION FIRE
2 3 7
2 4 6
2 6 4
2 7 3
4 1 7
4 2 6
4 3 5
4 5 3
4 6 2
4 7 1
6 1 5
6 2 4
6 4 2
6 5 1</pre>
=={{header|Maple}}==
<
exclusive_numbers := proc(i, j, k)
if (i = j) or (i = k) or (j = k) then
Line 2,504 ⟶ 2,980:
department_numbers();
</syntaxhighlight>
{{out|Output}}
<pre>
Line 2,525 ⟶ 3,001:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
{{out}}
<pre>{{2, 3, 7}, {2, 4, 6}, {2, 6, 4}, {2, 7, 3}, {4, 1, 7}, {4, 2, 6}, {4, 3, 5}, {4, 5, 3},
{4, 6, 2}, {4, 7, 1}, {6, 1, 5}, {6, 2, 4}, {6, 4, 2}, {6, 5, 1}}</pre>
=={{header|MATLAB}}==
<syntaxhighlight lang="MATLAB">
% Execute the functions
clear all;close all;clc;
sol = findsolution();
disp(table(sol(:, 1), sol(:, 2), sol(:, 3), 'VariableNames',{'Pol.','Fire','San.'}))
function sol = findsolution()
rng = 1:7;
sol = [];
for p = rng
for f = rng
for s = rng
if p ~= s && s ~= f && f ~= p && p + s + f == 12 && mod(p, 2) == 0
sol = [sol; p s f];
end
end
end
end
end
</syntaxhighlight>
{{out}}
<pre>
Pol. Fire San.
____ ____ ____
2 7 3
2 6 4
2 4 6
2 3 7
4 7 1
4 6 2
4 5 3
4 3 5
4 2 6
4 1 7
6 5 1
6 4 2
6 2 4
6 1 5
</pre>
=={{header|MiniScript}}==
{{trans|Kotlin}}
<syntaxhighlight lang="miniscript">print "Police Sanitation Fire"
print "------ ---------- ----"
count = 0
for h in range(1, 3)
i = h * 2
for j in range(1, 7)
if j != i then
for k in range(1, 7)
if k != i and k != j and i + j + k == 12 then
print " " + i + " " + j + " " + k
count += 1
end if
end for
end if
end for
end for
print char(10) + count + " valid combinations"</syntaxhighlight>
{{out}}
<pre>Police Sanitation Fire
------ ---------- ----
2 3 7
2 4 6
2 6 4
2 7 3
4 1 7
4 2 6
4 3 5
4 5 3
4 6 2
4 7 1
6 1 5
6 2 4
6 4 2
6 5 1
14 valid combinations
</pre>
=={{header|Modula-2}}==
<
FROM Conversions IMPORT IntToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 2,575 ⟶ 3,135:
ReadChar;
END DepartmentNumbers.</
=={{header|Mercury}}==
<
:- interface.
Line 2,606 ⟶ 3,166:
Police \= Fire,
Sanitation \= Fire,
Police + Sanitation + Fire = 12.</
{{out}}
<pre>P S F
Line 2,625 ⟶ 3,185:
=={{header|Nim}}==
<
iterator solutions(max, total: Positive): Solution =
Line 2,637 ⟶ 3,197:
echo "P S F"
for sol in solutions(7, 12):
echo sol.p, " ", sol.s, " ", sol.f</
{{out}}
Line 2,658 ⟶ 3,218:
=={{header|Objeck}}==
{{Trans|C++}}
<
function : Main(args : String[]) ~ Nil {
sol := 1;
Line 2,673 ⟶ 3,233:
};
}
}</
Output:
Line 2,695 ⟶ 3,255:
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">(*
* Caution: This is my first Ocaml program and anyone with Ocaml experience probably thinks it's horrible
* So please don't use this as an example for "good ocaml code" see it more as
Line 2,760 ⟶ 3,320:
print_sfp_list result;
</syntaxhighlight>
{{out}}
<pre>S F P
Line 2,781 ⟶ 3,341:
=={{header|PARI/GP}}==
<
{{out}}
<pre>2 3 7
Line 2,800 ⟶ 3,360:
=={{header|Perl}}==
<syntaxhighlight lang="perl">
#!/usr/bin/perl
Line 2,831 ⟶ 3,391:
}
}
</syntaxhighlight>
Above Code cleaned up and shortened
<syntaxhighlight lang="perl">
#!/usr/bin/perl
Line 2,856 ⟶ 3,416:
}
}
</syntaxhighlight>
Output:
<syntaxhighlight lang="perl">
Police - Fire - Sanitation
2 - 3 - 7
Line 2,875 ⟶ 3,435:
6 - 4 - 2
6 - 5 - 1
</syntaxhighlight>
===Alternate with Regex===
<
use strict; # https://rosettacode.org/wiki/Department_numbers
Line 2,887 ⟶ 3,447:
/(.).* \s .*?(?!\1)(.).* \s .*(?!\1)(?!\2)(.)
(??{$1+$2+$3!=12})
(?{ print "@{^CAPTURE}\n" })(*FAIL)/x;</
{{out}}
<pre>
Line 2,908 ⟶ 3,468:
</pre>
===Alternate with Glob===
<
use strict; # https://rosettacode.org/wiki/Department_numbers
Line 2,917 ⟶ 3,477:
print tr/+/ /r, "\n" for
grep !/(\d).*\1/ && 12 == eval,
glob '{2,4,6}' . '+{1,2,3,4,5,6,7}' x 2;</
Output same as with Regex
=={{header|Phix}}==
<!--<
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Police Sanitation Fire\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"------ ---------- ----\n"</span><span style="color: #0000FF;">)</span>
Line 2,940 ⟶ 3,500:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n%d solutions found\n"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">solutions</span><span style="color: #0000FF;">)</span>
<!--</
{{out}}
<pre>
Line 2,965 ⟶ 3,525:
=={{header|PHP}}==
<
$valid = 0;
Line 2,977 ⟶ 3,537:
}
}
echo $valid, ' valid combinations found.', PHP_EOL;</
{{out}}
Line 2,995 ⟶ 3,555:
Police: 6, Sanitation: 5, Fire: 1
14 valid combinations found.</pre>
=={{header|Picat}}==
===Constraint model===
<syntaxhighlight lang="picat">import cp.
go ?=>
N = 7,
Sols = findall([P,S,F], department_numbers(N, P,S,F)),
println(" P S F"),
foreach([P,S,F] in Sols)
printf("%2d %2d %2d\n",P,S,F)
end,
nl,
printf("Number of solutions: %d\n", Sols.len),
nl.
go => true.
department_numbers(N, Police,Sanitation,Fire) =>
Police :: 1..N,
Sanitation :: 1..N,
Fire :: 1..N,
all_different([Police,Sanitation,Fire]),
Police + Sanitation + Fire #= 12,
Police mod 2 #= 0,
solve([Police,Sanitation,Fire]).</syntaxhighlight>
{{out}}
<pre> P S F
2 3 7
2 4 6
2 6 4
2 7 3
4 1 7
4 2 6
4 3 5
4 5 3
4 6 2
4 7 1
6 1 5
6 2 4
6 4 2
6 5 1
Number of solutions: 14</pre>
===Loop===
<syntaxhighlight lang="picat">go2 => department_numbers2(N) =>
println(" P S F"),
foreach(P in 1..N, P mod 2 == 0)
foreach(S in 1..N, P != S)
foreach(F in 1..N, F != P, F != S, P + S + F == 12)
printf("%2d %2d %2d\n",P,S,F)
end
end
end.</syntaxhighlight>
===List comprehension===
<syntaxhighlight lang="picat">import util.
department_numbers3(N) =>
println("P S F"),
L = [[P.to_string,S.to_string,F.to_string] : P in 1..N, P mod 2 == 0,
S in 1..N, P != S,
F in 1..N,
F != P, F != S, P + S + F == 12],
println(map(L,join).join("\n")).</syntaxhighlight>
===Prolog style===
{{trans|Prolog}}
<syntaxhighlight lang="picat">go :-
println("P F S"),
assign(Police, Fire, Sanitation),
printf("%w %w %w\n", Police, Fire, Sanitation),
fail,
nl.
dept(X) :- between(1, 7, X).
police(X) :- member(X, [2, 4, 6]).
fire(X) :- dept(X).
san(X) :- dept(X).
assign(A, B, C) :-
police(A), fire(B), san(C),
A != B, A != C, B != C,
12 is A + B + C.</syntaxhighlight>
=={{header|PicoLisp}}==
<
(co 'numbers
(let N 7
Line 3,014 ⟶ 3,663:
(<> 12 (apply + L))
(println L) ) ) ) )
(departments)</
{{out}}
<pre>
Line 3,034 ⟶ 3,683:
===Pilog===
<
(member @Pol (2 4 6))
(for @Fire 1 7)
Line 3,043 ⟶ 3,692:
(^ @
(= 12
(+ (-> @Pol) (-> @Fire) (-> @San)) ) ) )</
{{out}}
<pre>
Line 3,065 ⟶ 3,714:
=={{header|Prolog}}==
<
dept(X) :- between(1, 7, X).
Line 3,083 ⟶ 3,732:
?- main.
</syntaxhighlight>
{{Out}}
<pre>
Line 3,101 ⟶ 3,750:
6 4 2
6 5 1
</pre>
=={{header|PL/M}}==
{{Trans|ALGOL W}}
{{works with|8080 PL/M Compiler}} ... under CP/M (or an emulator)
<syntaxhighlight lang="plm">
100H: /* SHOW POSSIBLE DEPARTMENT NUMBERS FOR POLICE, SANITATION AND FIRE */
/* THE POLICE DEPARTMENT NUMBER MUST BE EVEN, ALL DEPARTMENT NUMBERS */
/* MUST BE IN THE RANGE 1 .. 7 AND THE NUMBERS MUST SUM TO 12 */
/* CP/M SYSTEM CALL AND I/O ROUTINES */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
PR$NL: PROCEDURE; CALL PR$CHAR( 0DH ); CALL PR$CHAR( 0AH ); END;
PR$NUMBER: PROCEDURE( N ); /* PRINTS A NUMBER IN THE MINIMUN FIELD WIDTH */
DECLARE N ADDRESS;
DECLARE V ADDRESS, N$STR ( 6 )BYTE, W BYTE;
V = N;
W = LAST( N$STR );
N$STR( W ) = '$';
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
DO WHILE( ( V := V / 10 ) > 0 );
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
END;
CALL PR$STRING( .N$STR( W ) );
END PR$NUMBER;
/* TASK */
DECLARE MAX$DEPARTMENT$NUMBER LITERALLY '7';
DECLARE DEPARTMENT$SUM LITERALLY '12';
DECLARE ( POLICE, SANITATION, FIRE ) BYTE;
CALL PR$STRING( .'POLICE SANITATION FIRE$' );
CALL PR$NL;
DO POLICE = 2 TO MAX$DEPARTMENT$NUMBER BY 2;
DO SANITATION = 1 TO MAX$DEPARTMENT$NUMBER;
IF SANITATION <> POLICE THEN DO;
FIRE = ( DEPARTMENT$SUM - POLICE ) - SANITATION;
IF FIRE <= MAX$DEPARTMENT$NUMBER
AND FIRE <> SANITATION
AND FIRE <> POLICE
THEN DO;
CALL PR$STRING( .' $' ); CALL PR$NUMBER( POLICE );
CALL PR$STRING( .' $' ); CALL PR$NUMBER( SANITATION );
CALL PR$STRING( .' $' ); CALL PR$NUMBER( FIRE );
CALL PR$NL;
END;
END;
END;
END;
EOF
</syntaxhighlight>
{{out}}
<pre>
POLICE SANITATION FIRE
2 3 7
2 4 6
2 6 4
2 7 3
4 1 7
4 2 6
4 3 5
4 5 3
4 6 2
4 7 1
6 1 5
6 2 4
6 4 2
6 5 1
</pre>
=={{header|Python}}==
===Procedural===
<
def solve():
Line 3,117 ⟶ 3,838:
if __name__ == '__main__':
solve()</
{{out}}
Line 3,139 ⟶ 3,860:
Expressing the options directly and declaratively in terms of a ''bind'' operator, without importing ''permutations'':
{{Works with|Python|3}}
<
from itertools import (chain)
Line 3,208 ⟶ 3,929:
if __name__ == '__main__':
main()</
{{Out}}
<pre>('Police', 'Sanitation', 'Fire')
Line 3,232 ⟶ 3,953:
Nested ''bind'' (or ''concatMap'') expressions (like those above) can also be translated into list comprehension notation:
{{Works with|Python|3.7}}
<
from operator import ne
Line 3,308 ⟶ 4,029:
if __name__ == '__main__':
main()</
{{Out}}
<pre>('Police', 'Sanitation', 'Fire')
Line 3,329 ⟶ 4,050:
===Adapted from C# Example===
<
# We start with the Police Department.
# Range is the start, stop, and step. This returns only even numbers.
Line 3,345 ⟶ 4,066:
print("Police: ", p, " Sanitation:", f, " Fire: ", s)
</syntaxhighlight>
{{Out}}
<pre>
Line 3,363 ⟶ 4,084:
Police: 6 Sanitation: 4 Fire: 2
</pre>
===Using a constraint solver===
A problem this trivial is amenable to brute-force solutions such as the above, but it is a good example of the type of problem for which a constraint solver can be useful. This is how one could solve it using the `python-constraint` library:
{{libheader|python-constraint}}
<syntaxhighlight lang="python">import constraint
depts = ( 'police', 'sanitation', 'fire' )
p = constraint.Problem()
for var in depts:
p.addVariable(var, range(1,8))
p.addConstraint(constraint.AllDifferentConstraint())
p.addConstraint(lambda *vars: sum(vars)==12, depts)
p.addConstraint(lambda p: p%2==0, ('police',))
for s in p.getSolutions():
print(s)</syntaxhighlight>
{{Out}}
<pre>{'police': 6, 'fire': 5, 'sanitation': 1}
{'police': 6, 'fire': 4, 'sanitation': 2}
{'police': 6, 'fire': 2, 'sanitation': 4}
{'police': 6, 'fire': 1, 'sanitation': 5}
{'police': 4, 'fire': 6, 'sanitation': 2}
{'police': 4, 'fire': 7, 'sanitation': 1}
{'police': 4, 'fire': 5, 'sanitation': 3}
{'police': 4, 'fire': 3, 'sanitation': 5}
{'police': 4, 'fire': 2, 'sanitation': 6}
{'police': 4, 'fire': 1, 'sanitation': 7}
{'police': 2, 'fire': 4, 'sanitation': 6}
{'police': 2, 'fire': 6, 'sanitation': 4}
{'police': 2, 'fire': 7, 'sanitation': 3}
{'police': 2, 'fire': 3, 'sanitation': 7}</pre>
=={{header|Quackery}}==
Line 3,368 ⟶ 4,126:
{{trans|Forth}}
<
[ 2drop drop ] done
dip over swap over = iff
Line 3,393 ⟶ 4,151:
witheach police ] is departments ( --> )
departments</
{{out}}
Line 3,414 ⟶ 4,172:
=={{header|R}}==
We solve this task in two lines. The rest of the code is to make the result look nice.
<
solution <- allPermutations[which(rowSums(allPermutations)==12 & apply(allPermutations, 1, function(x) !any(duplicated(x)))),]
solution <- solution[order(solution$Police, solution$Sanitation),]
row.names(solution) <- paste0("Solution #", seq_len(nrow(solution)), ":")
print(solution)</
{{out}}
Line 3,441 ⟶ 4,199:
We filter the Cartesian product of the lists of candidate department numbers.
<
(cons '(police fire sanitation)
(filter (λ (pfs) (and (not (check-duplicates pfs))
Line 3,447 ⟶ 4,205:
pfs))
(cartesian-product (range 2 8 2) (range 1 8) (range 1 8))))
</syntaxhighlight>
{{out}}
Line 3,469 ⟶ 4,227:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
for .permutations\ .grep(*.[0] %% 2) {
say <police fire sanitation> Z=> .list;
}
}
</syntaxhighlight>
{{out}}
<pre>
Line 3,495 ⟶ 4,253:
=={{header|REXX}}==
This REXX example essentially uses brute force approach for so simple a puzzle.
<
say 'police sanitation fire' /*display simple title for the output*/
say '══════ ══════════ ════' /* " head separator " " " */
Line 3,511 ⟶ 4,269:
say '══════ ══════════ ════' /* " head separator " " " */
say /*stick a fork in it, we're all done. */
say # ' solutions found.' /*also, show the # of solutions found. */</
{{out|output|text= when using the default inputs:}}
<pre>
Line 3,536 ⟶ 4,294:
=={{header|Ring}}==
<
sanitation= 0
see "police fire sanitation" + nl
Line 3,554 ⟶ 4,312:
next
next
</syntaxhighlight>
Output:
<pre>
Line 3,574 ⟶ 4,332:
</pre>
=={{header|RPL}}==
≪ { }
<span style="color:red">2 6</span> '''FOR''' police
<span style="color:red">1 7</span> '''FOR''' sanitation
'''IF''' police sanitation ≠ '''THEN'''
<span style="color:red">12</span> police - sanitation -
'''IF''' DUP <span style="color:red">0</span> >
OVER <span style="color:red">7</span> ≤ AND
OVER police ≠ AND
OVER sanitation ≠ AND
'''THEN'''
police sanitation ROT
<span style="color:red">3</span> →ARRY +
'''ELSE''' DROP '''END'''
'''END'''
'''NEXT'''
<span style="color:red">2</span> '''STEP'''
DUP SIZE
≫ '<span style="color:blue">PSF</span>' STO
{{out}}
<pre>
2: { [ 2 3 7 ] [ 2 4 6 ] [ 2 6 4 ] [ 2 7 3 ] [ 4 1 7 ] [ 4 2 6 ] [ 4 3 5 ] [ 4 5 3 ] [ 4 6 2 ] [ 4 7 1 ] [ 6 1 5 ] [ 6 2 4 ] [ 6 4 2 ] [ 6 5 1 ] }
1: 14
</pre>
=={{header|Ruby}}==
<
(1..7).to_a.permutation(3){|p| puts p.join if p.first.even? && p.sum == 12 }
</syntaxhighlight>
{{Output}}
<pre>237
Line 3,597 ⟶ 4,380:
=={{header|Rust}}==
{{trans|C}}
<
fn main() {
println!("Police Sanitation Fire");
Line 3,615 ⟶ 4,398:
}
}
}</
=={{header|Scala}}==
<
(1 to 7).permutations.map{ n => (n(0),n(1),n(2)) }.toList.distinct // All permutations of possible department numbers
.filter{ n => n._1 % 2 == 0 } // Keep only even numbers favored by Police Chief
Line 3,628 ⟶ 4,411:
println( depts.mkString("\n") )
}
</syntaxhighlight>
{{output}}
<pre>(Police, Sanitation, Fire)
Line 3,649 ⟶ 4,432:
=={{header|Sidef}}==
{{trans|Raku}}
<
a.sum == 12 || next
a.permutations {|*b|
Line 3,655 ⟶ 4,438:
say (%w(police fire sanitation) ~Z b -> join(" "))
}
})</
{{out}}
<pre>
Line 3,678 ⟶ 4,461:
Functional approach:
<
return (1...7)
.filter({ $0 != x })
Line 3,694 ⟶ 4,477:
for result in res {
print(result)
}</
Iterative approach:
<
for x in [2, 4, 6] {
Line 3,714 ⟶ 4,497:
for result in res {
print(result)
}</
{{out}}
Line 3,737 ⟶ 4,520:
<b>VERSION A</b> - using procedures and list operations
<
# Procedure named ".." returns list of integers from 1 to max.
proc .. max {
Line 3,792 ⟶ 4,575:
}
puts "$valid valid combinations found."
</syntaxhighlight>
<b>VERSION B</b> - using simple for loops with number literals
<
set valid 0
for {set police 2} {$police <= 6} {incr police 2} {
Line 3,809 ⟶ 4,592:
}
puts "$valid valid combinations found."
</syntaxhighlight>
<b>VERSION C</b> - using simple for loops with number variables
<
set min 1
set max 7
Line 3,830 ⟶ 4,613:
puts "$valid valid combinations found."
</syntaxhighlight>
<b>VERSION D</b> - using list filter with lambda expressions
<
# Procedure named ".." returns list of integers from 1 to max.
proc .. max {
Line 3,886 ⟶ 4,669:
puts [join $numbersOk \n]
puts "[llength $numbersOk] valid combinations found."
</syntaxhighlight>
{{output}}
All four versions (A, B, C and D) produce the same result:
Line 3,908 ⟶ 4,691:
=={{header|Tiny BASIC}}==
<
PRINT "------|----------|----"
10 LET P = P + 2
Line 3,921 ⟶ 4,704:
IF F < 7 THEN GOTO 30
IF S < 7 THEN GOTO 20
IF P < 6 THEN GOTO 10</
=={{header|Transd}}==
<
MainModule : {
Line 3,934 ⟶ 4,717:
(if (eq (+ i j k) 12) (lout i " " j " " k)))))
)
}</
<pre>
Police | Sanit. | Fire
Line 3,953 ⟶ 4,736:
</pre>
== {{header|TypeScript}} ==
{{trans|Sinclair ZX81 BASIC}}
<syntaxhighlight lang="javascript">
// Department numbers
console.log(`POLICE SANITATION FIRE`);
let f: number;
for (var p = 2; p <= 7; p += 2) {
for (var s = 1; s <= 7; s++) {
if (s != p) {
f = (12 - p) - s;
if ((f > 0) && (f <= 7) && (f != s) && (f != p))
console.log(` ${p} ${s} ${f}`);
}
}
}
</syntaxhighlight>
{{out}}
<pre>
POLICE SANITATION FIRE
2 3 7
2 4 6
2 6 4
2 7 3
4 1 7
4 2 6
4 3 5
4 5 3
4 6 2
4 7 1
6 1 5
6 2 4
6 4 2
6 5 1
</pre>
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
{{works with|Korn Shell}}
{{works with|Z Shell}}
<syntaxhighlight lang="bash">function main {
set -- Police Sanitation Fire
typeset -i pw=${#1} sw=${#2} fw=${#3}
printf '%s' "$1"
shift
printf '\t%s' "$@"
printf '\n'
for (( p=2; p<8; p+=2 )); do
for (( s=1; s<8; ++s )); do
if (( s == p )); then
continue
fi
(( f = 12 - p - s ))
if (( f == s || f == p || f < 1 || f > 7 )); then
continue
fi
printf "%${pw}d\t%${sw}d\t%${fw}d\n" "$p" "$s" "$f"
done
done
}
main "$@"</syntaxhighlight>
{{Out}}
<pre>Police Sanitation Fire
2 3 7
2 4 6
2 6 4
2 7 3
4 1 7
4 2 6
4 3 5
4 5 3
4 6 2
4 7 1
6 1 5
6 2 4
6 4 2
6 5 1</pre>
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Sub Main()
Line 3,977 ⟶ 4,840:
End Sub
End Module</
{{out}}
<pre>Police:2, Sanitation:3, Fire:7
Line 3,993 ⟶ 4,856:
Police:6, Sanitation:2, Fire:4
Police:6, Sanitation:4, Fire:2</pre>
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="go">fn main() {
println("Police Sanitation Fire")
println("------ ---------- ----")
mut count := 0
for i := 2; i < 7; i += 2 {
for j in 1..8 {
if j == i { continue }
for k in 1..8 {
if k == i || k == j { continue }
if i + j + k != 12 { continue }
println(" $i $j $k")
count++
}
}
}
println("\n$count valid combinations")
}</syntaxhighlight>
{{out}}
<pre>
Police Sanitation Fire
------ ---------- ----
2 3 7
2 4 6
2 6 4
2 7 3
4 1 7
4 2 6
4 3 5
4 5 3
4 6 2
4 7 1
6 1 5
6 2 4
6 4 2
6 5 1
14 valid combinations
</pre>
=={{header|VTL-2}}==
<syntaxhighlight lang="vtl2">10 P=2
20 S=1
30 F=1
40 #=0<((P=S)+(P=F)+(S=F)+(P+S+F=12=0))*110
50 ?=P
60 $=32
70 ?=S
80 $=32
90 ?=F
100 ?=""
110 F=F+1
120 #=F<8*40
130 S=S+1
140 #=S<8*30
150 P=P+2
160 #=P<8*20</syntaxhighlight>
{{out}}
<pre>2 3 7
2 4 6
2 6 4
2 7 3
4 1 7
4 2 6
4 3 5
4 5 3
4 6 2
4 7 1
6 1 5
6 2 4
6 4 2
6 5 1</pre>
=={{header|Wren}}==
{{trans|Kotlin}}
<
System.print("------ ---------- ----")
var count = 0
Line 4,012 ⟶ 4,950:
}
}
System.print("\n%(count) valid combinations")</
{{out}}
Line 4,035 ⟶ 4,973:
14 valid combinations
</pre>
=={{header|XPL0}}==
{{trans|Sinclair ZX81 BASIC}}
{{works with|EXPL-32}}
<syntaxhighlight lang="xpl0">
\Department numbers
code CrLf=9, IntIn=10, IntOut=11, Text=12;
integer P, S, F;
begin
Text(0, "POLICE SANITATION FIRE");
CrLf(0);
P:= 2;
while P <= 7 do
begin
for S:= 1, 7 do
if S # P then
begin
F:= (12 - P) - S;
if (F > 0) & (F <= 7) & (F # S) & (F # P) then
begin
Text(0, " "); IntOut(0, P);
Text(0, " "); IntOut(0, S);
Text(0, " "); IntOut(0, F);
CrLf(0)
end
end;
P:= P + 2
end;
end
</syntaxhighlight>
{{out}}
<pre>
POLICE SANITATION FIRE
2 3 7
2 4 6
2 6 4
2 7 3
4 1 7
4 2 6
4 3 5
4 5 3
4 6 2
4 7 1
6 1 5
6 2 4
6 4 2
6 5 1
</pre>
=={{header|Zig}}==
{{works with|Zig|0.11.0dev}}
<syntaxhighlight lang="zig">const std = @import("std");</syntaxhighlight>
<syntaxhighlight lang="zig">pub fn main() !void {
const stdout = std.io.getStdOut().writer();
try stdout.writeAll("Police Sanitation Fire\n");
try stdout.writeAll("------ ---------- ----\n");
var p: usize = 2;
while (p <= 7) : (p += 2)
for (1..7 + 1) |s|
for (1..7 + 1) |f|
if (p != s and s != f and f != p and p + f + s == 12) {
try stdout.print(" {d} {d} {d}\n", .{ p, s, f });
};
}</syntaxhighlight>
{{out}}
<pre>Police Sanitation Fire
------ ---------- ----
2 3 7
2 4 6
2 6 4
2 7 3
4 1 7
4 2 6
4 3 5
4 5 3
4 6 2
4 7 1
6 1 5
6 2 4
6 4 2
6 5 1</pre>
===Zig using an iterator===
{{works with|Zig|0.11.0}}
Using a Zig ''struct'' to create an iterator is a common pattern in Zig.
<syntaxhighlight lang="zig">
const std = @import("std");
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
try stdout.writeAll("Police Sanitation Fire\n");
try stdout.writeAll("------ ---------- ----\n");
var it = SolutionIterator.init();
while (it.next()) |solution| {
try stdout.print(
" {d} {d} {d}\n",
.{ solution.police, solution.sanitation, solution.fire },
);
}
}
/// 3 bit unsigned (u3) limits 0 <= department <= 7
const Departments = packed struct {
police: u3,
sanitation: u3,
fire: u3,
};
const DepartmentsUnion = packed union {
departments: Departments,
together: u9,
};
const SolutionIterator = struct {
// police is initialized to one as adding one is the first operation in next()
// with the result .police == 2 (an even number) on the first pass.
u: DepartmentsUnion = .{ .departments = .{ .police = 1, .sanitation = 1, .fire = 1 } },
/// init() returns an initialised structure.
/// Using init() is a common Zig pattern.
fn init() SolutionIterator {
return SolutionIterator{};
}
fn next(self: *SolutionIterator) ?Departments {
if (self.u.together == 0) return null; // already completed
while (true) {
const ov = @addWithOverflow(self.u.together, 1);
if (ov[1] == 1) {
self.u.together = 0;
return null; // overflowed, completed
} else {
self.u.together = ov[0];
// None can be zero
if (self.u.departments.police == 0) self.u.departments.police = 2; // even
if (self.u.departments.sanitation == 0) self.u.departments.sanitation = 1;
if (self.u.departments.fire == 0) self.u.departments.fire = 1;
// Police must be even
if (self.u.departments.police & 1 == 1)
continue;
// No two can be the same
if (self.u.departments.police == self.u.departments.sanitation) continue;
if (self.u.departments.sanitation == self.u.departments.fire) continue;
if (self.u.departments.fire == self.u.departments.police) continue;
// Must total twelve (maximum sum 7 + 7 + 7 = 21 requires 5 bits)
const p = @as(u5, self.u.departments.police);
const s = @as(u5, self.u.departments.sanitation);
const f = @as(u5, self.u.departments.fire);
if (p + s + f != 12)
continue;
return self.u.departments;
}
}
}
};
</syntaxhighlight>
=={{header|zkl}}==
<
.filter(fcn(numbers){ numbers.sum(0)==12 }) // which all sum to 12 (==5)
.println();</
{{output}}
<pre>
Line 4,049 ⟶ 5,149:
For a table with repeated solutions using nested loops:
<
foreach p,f,s in ([2..7,2], [1..7], [1..7])
{ if((p!=s!=f) and p+f+s==12) println(p,"\t",f,"\t",s) }</
{{out}}
<pre>
|