Department numbers: Difference between revisions

m
(Department numbers in Asymptote)
 
(29 intermediate revisions by 14 users not shown)
Line 28:
=={{header|11l}}==
{{trans|C}}
<langsyntaxhighlight lang="11l">print(‘Police Sanitation Fire’)
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)</langsyntaxhighlight>
{{Output}}
<pre>
Line 57:
 
=={{header|8080 Assembly}}==
<langsyntaxhighlight lang="8080asm"> org 100h
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</langsyntaxhighlight>
 
{{out}}
Line 128:
=={{header|8086 Assembly}}==
 
<langsyntaxhighlight lang="asm"> cpu 8086
bits 16
org 100h
Line 177:
section .data
ohdr: db 'P S F',13,10 ; Header
obuf: equ $ ; Place to write output</langsyntaxhighlight>
 
{{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!}}==
<langsyntaxhighlight Actionlang="action!">PROC Main()
BYTE p,s,f
 
Line 216 ⟶ 249:
OD
OD
RETURN</langsyntaxhighlight>
{{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}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Department_Numbers is
Line 259 ⟶ 292:
end loop;
end loop;
end Department_Numbers;</langsyntaxhighlight>
 
{{out}}
Line 281 ⟶ 314:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">integer p, s, f;
 
p = 0;
Line 294 ⟶ 327:
}
}
}</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
As noted in the Fortran sample, once the police and sanitation departments are posited, the fire department value is fixed
<langsyntaxhighlight lang="algol68">BEGIN
# 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</langsyntaxhighlight>
{{out}}
<pre>
Line 345 ⟶ 378:
=={{header|ALGOL W}}==
{{Trans|ALGOL 68}}
<langsyntaxhighlight lang="algolw">begin
% 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.</langsyntaxhighlight>
{{out}}
<pre>
Line 386 ⟶ 419:
=={{header|APL}}==
 
<langsyntaxhighlight APLlang="apl">'PSF'⍪(⊢(⌿⍨)((∪≡⊢)¨↓∧(0=2|1⌷[2]⊢)∧12=+/))↑,⍳3/7</langsyntaxhighlight>
 
This prints each triplet of numbers from 1 to 7 for which:
Line 415 ⟶ 448:
Briefly, composing a solution from generic functions:
 
<langsyntaxhighlight AppleScriptlang="applescript">on run
script
on |λ|(x)
Line 479 ⟶ 512:
on unlines(xs)
intercalate(linefeed, xs)
end unlines</langsyntaxhighlight>
{{Out}}
<pre>237
Line 499 ⟶ 532:
{{Trans|JavaScript}}
{{Trans|Haskell}}
<langsyntaxhighlight AppleScriptlang="applescript">-- NUMBERING CONSTRAINTS ------------------------------------------------------
 
-- options :: Int -> Int -> Int -> [(Int, Int, Int)]
Line 672 ⟶ 705:
on unlines(xs)
intercalate(linefeed, xs)
end unlines</langsyntaxhighlight>
{{Out}}
<pre>(Police, Sanitation, Fire)
Line 695 ⟶ 728:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">loop 1..7 'x [
loop 1..7 'y [
loop 1..7 'z [
Line 705 ⟶ 738:
]
]
]</langsyntaxhighlight>
 
{{out}}
Line 725 ⟶ 758:
 
=={{header|Asymptote}}==
<langsyntaxhighlight Asymptotelang="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);
Line 737 ⟶ 770:
}
}
}</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">perm(elements, n, opt:="", Delim:="", str:="", res:="", j:=0, dup:="") {
res := IsObject(res) ? res : [], dup := IsObject(dup) ? dup : []
if (n > j)
Line 755 ⟶ 788:
Sort, res, D`n
return StrReplace(res, "`n", Delim)
}</langsyntaxhighlight>
Example:<langsyntaxhighlight AutoHotkeylang="autohotkey">elements := "1234567", n := 3
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 762 ⟶ 795:
 
MsgBox, 262144, , % res4
return</langsyntaxhighlight>
Outputs:<pre>237
246
Line 779 ⟶ 812:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f DEPARTMENT_NUMBERS.AWK
BEGIN {
Line 800 ⟶ 833:
return(stmt1 stmt2 stmt3)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 821 ⟶ 854:
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
let start() be
Line 828 ⟶ 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)</langsyntaxhighlight>
{{out}}
<pre>2 3 7
Line 849 ⟶ 882:
The [[#Sinclair_ZX81_BASIC|Sinclair ZX81 BASIC]] solution works without any changes.
==={{header|BASIC256}}===
<langsyntaxhighlight BASIC256lang="basic256">print "--police-- --sanitation-- --fire--"
 
for police = 2 to 7 step 2
Line 860 ⟶ 893:
end if
next fire
next police</langsyntaxhighlight>
{{out}}
<pre>--police-- --sanitation-- --fire--
Line 877 ⟶ 910:
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}}===
<langsyntaxhighlight lang="runbasic">print "police fire sanitation"
 
for police = 2 to 7 step 2
Line 889 ⟶ 977:
[cont]
next fire
next police</langsyntaxhighlight>
 
==={{header|PureBasic}}===
<langsyntaxhighlight PureBasiclang="purebasic">OpenConsole()
PrintN("--police-- --sanitation-- --fire--")
 
Line 909 ⟶ 997:
 
Input()
CloseConsole()</langsyntaxhighlight>
{{out}}
<pre>Same as BASIC256 entry.</pre>
 
==={{header|Yabasic}}===
<langsyntaxhighlight lang="freebasic">print "--police-- --sanitation-- --fire--"
 
for police = 2 to 7 step 2
Line 923 ⟶ 1,011:
if sanitation >= 1 and sanitation <= 7 print police using "######", fire using "############", sanitation using "###########"
next fire
next police</langsyntaxhighlight>
{{out}}
<pre>Same as BASIC256 entry.</pre>
Line 929 ⟶ 1,017:
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">100 PRINT "Police","San.","Fire"
110 FOR P=2 TO 7 STEP 2
120 FOR S=1 TO 7
Line 937 ⟶ 1,025:
141 END IF
150 NEXT
160 NEXT</langsyntaxhighlight>
 
==={{header|Minimal BASIC}}===
{{trans|Sinclair ZX81 BASIC}}
<syntaxhighlight lang="basic">
<lang gwbasic>
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 90120
60 LET F = (12-P)-S
70 IF F <= 0 OR F > 7 OR F = S OR F = P THEN 90120
80 IF F > 7 THEN 120
80 PRINT TAB(3); P; TAB(11); S; TAB(19); F
90 NEXTIF F = S THEN 120
100 NEXTIF F = P THEN 120
110 PRINT TAB(3); P; TAB(11); S; TAB(19); F
110 END
120 NEXT S
</lang>
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.
<langsyntaxhighlight lang="basic">10 PRINT "POLICE SANITATION FIRE"
20 FOR P=2 TO 7 STEP 2
30 FOR S=1 TO 7
Line 964 ⟶ 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</langsyntaxhighlight>
{{out}}
<pre>POLICE SANITATION FIRE
Line 984 ⟶ 1,108:
==={{header|BBC BASIC}}===
{{trans|ALGOL 68}}
<langsyntaxhighlight lang="bbcbasic">REM >deptnums
max_dept_num% = 7
dept_sum% = 12
Line 996 ⟶ 1,120:
NEXT
NEXT
END</langsyntaxhighlight>
{{out}}
<pre>police sanitation fire
Line 1,015 ⟶ 1,139:
 
==={{header|QBasic}}===
<langsyntaxhighlight lang="qbasic">PRINT "--police-- --sanitation-- --fire--"
 
FOR police = 2 TO 7 STEP 2
Line 1,027 ⟶ 1,151:
cont:
NEXT fire
NEXT police</langsyntaxhighlight>
 
==={{header|XBasic}}===
{{works with|Windows XBasic}}
<langsyntaxhighlight lang="xbasic">PROGRAM "Depar/num"
 
DECLARE FUNCTION Entry ()
Line 1,050 ⟶ 1,174:
NEXT police
END FUNCTION
END PROGRAM </langsyntaxhighlight>
 
=={{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">
<lang C>
#include<stdio.h>
 
Line 1,076 ⟶ 1,200:
return 0;
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,098 ⟶ 1,222:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
public class Program
{
Line 1,113 ⟶ 1,237:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,133 ⟶ 1,257:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <iomanip>
Line 1,152 ⟶ 1,276:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,173 ⟶ 1,297:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(let [n (range 1 8)]
(for [police n
sanitation n
Line 1,180 ⟶ 1,304:
:when (even? police)
:when (= 12 (+ police sanitation fire))]
(println police sanitation fire)))</langsyntaxhighlight>
{{Out}}
<pre>
Line 1,200 ⟶ 1,324:
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">start_up = proc ()
po: stream := stream$primary_output()
Line 1,219 ⟶ 1,343:
end
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>P S F
Line 1,239 ⟶ 1,363:
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. DEPARTMENT-NUMBERS.
 
Line 1,275 ⟶ 1,399:
AND SANITATION IS NOT EQUAL TO FIRE
AND TOTAL IS EQUAL TO 12,
DISPLAY COMBINATION.</langsyntaxhighlight>
{{out}}
<pre>POLICE SANITATION FIRE
Line 1,294 ⟶ 1,418:
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
 
typedef Dpt is int(1, 7);
Line 1,323 ⟶ 1,447:
end loop;
pol := pol + 2;
end loop;</langsyntaxhighlight>
 
{{out}}
Line 1,346 ⟶ 1,470:
 
{{Trans|C++}}
<syntaxhighlight lang="d">
<lang D>
import std.stdio, std.range;
 
Line 1,362 ⟶ 1,486:
}
}
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,384 ⟶ 1,508:
{{libheader| System.SysUtils}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Department_numbers;
 
Line 1,420 ⟶ 1,544:
writeln(#10, count, ' valid combinations');
readln;
end.</langsyntaxhighlight>
 
=={{header|Draco}}==
<langsyntaxhighlight lang="draco">proc main() void:
byte police, sanitation, fire;
 
Line 1,439 ⟶ 1,563:
od
od
corp</langsyntaxhighlight>
{{out}}
<pre>Police Sanitation Fire
Line 1,456 ⟶ 1,580:
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}}==
<langsyntaxhighlight lang="elixir">
IO.puts("P - F - S")
for p <- [2,4,6],
Line 1,468 ⟶ 1,609:
|> Enum.each(&IO.puts/1)
 
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang="elixir">
P - F - S
2 - 3 - 7
Line 1,485 ⟶ 1,626:
6 - 4 - 2
6 - 5 - 1
</syntaxhighlight>
</lang>
 
=={{header|Excel}}==
Line 1,495 ⟶ 1,636:
 
{{Works with|Office 365 betas 2021}}
<langsyntaxhighlight lang="lisp">departmentNumbers
=validRows(
LAMBDA(ab,
Line 1,519 ⟶ 1,660:
)
)
)</langsyntaxhighlight>
 
and also assuming the following generic bindings in the Name Manager for the WorkBook:
 
<langsyntaxhighlight lang="lisp">cartesianProduct
=LAMBDA(xs,
LAMBDA(ys,
Line 1,565 ⟶ 1,706:
)
)
)</langsyntaxhighlight>
 
{{Out}}
Line 1,669 ⟶ 1,810:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
// 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>
</lang>
{{out}}
<pre>
Line 1,722 ⟶ 1,863:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting io kernel math math.combinatorics math.ranges
sequences sets ;
IN: rosetta-code.department-numbers
Line 1,730 ⟶ 1,871:
 
"{ Police, Sanitation, Fire }" print nl
[ "%[%d, %]\n" printf ] each</langsyntaxhighlight>
{{out}}
<pre>
Line 1,751 ⟶ 1,892:
</pre>
=={{header|Fermat}}==
<langsyntaxhighlight lang="fermat">!!'Police Sanitation Fire';
!!'------|----------|----';
for p = 2 to 6 by 2 do
Line 1,757 ⟶ 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;</langsyntaxhighlight>
{{out}}<pre>
Police Sanitation Fire
Line 1,778 ⟶ 1,919:
 
=={{header|FOCAL}}==
<langsyntaxhighlight lang="focal">01.10 F P=2,2,6;F S=1,7;F G=1,7;D 2
01.20 Q
 
Line 1,786 ⟶ 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</langsyntaxhighlight>
{{out}}
<pre>= 2= 3= 7
Line 1,804 ⟶ 1,945:
 
=={{header|Forth}}==
<langsyntaxhighlight Forthlang="forth">\ if department numbers are valid, print them on a single line
: fire ( pol san fir -- )
2dup = if 2drop drop exit then
Line 1,826 ⟶ 1,967:
\ tries to assign numbers with police = 2, 4, or 6
: departments cr \ leave input line
8 2 do i police 2 +loop ;</langsyntaxhighlight>
 
{{out}}
Line 1,855 ⟶ 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. <langsyntaxhighlight Fortranlang="fortran"> INTEGER P,S,F !Department codes for Police, Sanitation, and Fire. Values 1 to 7 only.
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,865 ⟶ 2,006:
8 END DO SS !Next S
9 END DO PP !Next P.
END !Well, that was straightforward.</langsyntaxhighlight>
Output:
<pre>
Line 1,885 ⟶ 2,026:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 15-08-2017
' compile with: fbc -s console
 
Line 1,908 ⟶ 2,049:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>police fire sanitation
Line 1,926 ⟶ 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]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim siC0, siC1, siC2 As Short
Dim sOut As New String[]
Line 1,952 ⟶ 2,145:
Next
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,974 ⟶ 2,167:
=={{header|Go}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,994 ⟶ 2,187:
}
fmt.Printf("\n%d valid combinations\n", count)
}</langsyntaxhighlight>
 
{{out}}
Line 2,020 ⟶ 2,213:
=={{header|Groovy}}==
{{trans|Java}}
<langsyntaxhighlight lang="groovy">class DepartmentNumbers {
static void main(String[] args) {
println("Police Sanitation Fire")
Line 2,039 ⟶ 2,232:
println("$count valid combinations")
}
}</langsyntaxhighlight>
{{out}}
<pre>Police Sanitation Fire
Line 2,061 ⟶ 2,254:
 
=={{header|GW-BASIC}}==
<langsyntaxhighlight lang="gwbasic">10 PRINT "Police Sanitation Fire"
20 PRINT "------|----------|----"
30 FOR P = 2 TO 7 STEP 2
Line 2,071 ⟶ 2,264:
90 NEXT F
100 NEXT S
110 NEXT P</langsyntaxhighlight>
 
=={{header|Haskell}}==
Bare minimum:
<langsyntaxhighlight lang="haskell">main :: IO ()
main =
mapM_ print $
Line 2,086 ⟶ 2,279:
case y /= z && 1 <= z && z <= 7 of
True -> [(x, y, z)]
_ -> []</langsyntaxhighlight>
or, resugaring this into list comprehension format:
<langsyntaxhighlight Haskelllang="haskell">main :: IO ()
main =
mapM_
Line 2,096 ⟶ 2,289:
, y <- [1 .. 7]
, z <- [12 - (x + y)]
, y /= z && 1 <= z && z <= 7 ]</langsyntaxhighlight>
Do notation:
<langsyntaxhighlight Haskelllang="haskell">main :: IO ()
main =
mapM_ print $
Line 2,106 ⟶ 2,299:
if y /= z && 1 <= z && z <= 7
then [(x, y, z)]
else []</langsyntaxhighlight>
Unadorned brute force – more than enough at this small scale:
<langsyntaxhighlight Haskelllang="haskell">import Data.List (nub)
 
main :: IO ()
Line 2,121 ⟶ 2,314:
\z ->
[ (x, y, z)
| even x && 3 == length (nub [x, y, z]) && 12 == sum [x, y, z] ]</langsyntaxhighlight>
{{Out}}
<pre>(2,3,7)
Line 2,139 ⟶ 2,332:
 
Or, more generally:
<langsyntaxhighlight Haskelllang="haskell">-------------------- DEPARTMENT NUMBERS ------------------
 
options :: Int -> Int -> Int -> [(Int, Int, Int)]
Line 2,166 ⟶ 2,359:
[ "\nNumber of options: ",
show (length xs)
]</langsyntaxhighlight>
 
Reaching again for a little more syntactic sugar, the options function above could also be re-written either as a list comprehension,
<langsyntaxhighlight Haskelllang="haskell">options :: Int -> Int -> Int -> [(Int, Int, Int)]
options lo hi total =
let ds = [lo .. hi]
Line 2,176 ⟶ 2,369:
, y <- filter (/= x) ds
, let z = total - (x + y)
, y /= z && lo <= z && z <= hi ]</langsyntaxhighlight>
 
or in Do notation:
<langsyntaxhighlight lang="haskell">import Control.Monad (guard)
 
options :: Int -> Int -> Int -> [(Int, Int, Int)]
Line 2,188 ⟶ 2,381:
let z = total - (x + y)
guard $ y /= z && lo <= z && z <= hi
return (x, y, z)</langsyntaxhighlight>
{{Out}}
<pre>(Police, Sanitation, Fire)
Line 2,212 ⟶ 2,405:
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j">require 'stats'
permfrom=: ,/@(perm@[ {"_ 1 comb) NB. get permutations of length x from y possible items
 
Line 2,223 ⟶ 2,416:
Validnums=: >: i.7 NB. valid Department numbers
 
getDeptNums=: [: (#~ conditions"1) Validnums {~ permfrom</langsyntaxhighlight>
'''Example usage:'''
<langsyntaxhighlight lang="j"> 3 getDeptNums 7
4 1 7
4 7 1
Line 2,239 ⟶ 2,432:
6 4 2
4 3 5
4 5 3</langsyntaxhighlight>
 
===Alternate approachapproaches===
 
<langsyntaxhighlight Jlang="j"> (/:"#. 2|]) (#~ 12=+/"1) 1+3 comb 7 [ load'stats'
4 1 7
6 1 5
2 3 7
2 4 6
4 3 5</langsyntaxhighlight>
 
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}}
<langsyntaxhighlight Javalang="java">public class DepartmentNumbers {
public static void main(String[] args) {
System.out.println("Police Sanitation Fire");
Line 2,272 ⟶ 2,492:
System.out.printf("\n%d valid combinations", count);
}
}</langsyntaxhighlight>
{{out}}
<pre>Police Sanitation Fire
Line 2,294 ⟶ 2,514:
===ES5===
Briefly:
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
'use strict';
 
Line 2,314 ⟶ 2,534:
.map(JSON.stringify)
.join('\n');
})();</langsyntaxhighlight>
{{Out}}
<pre>(Police, Sanitation, Fire)
Line 2,334 ⟶ 2,554:
Or, more generally:
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
'use strict';
 
Line 2,412 ⟶ 2,632:
return '(Police, Sanitation, Fire)\n\n' +
unlines(map(show, xs)) + '\n\nNumber of options: ' + length(xs);
})();</langsyntaxhighlight>
{{Out}}
<pre>(Police, Sanitation, Fire)
Line 2,435 ⟶ 2,655:
===ES6===
Briefly:
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
"use strict";
 
Line 2,456 ⟶ 2,676:
 
return `${label}\n${solutions}`;
})();</langsyntaxhighlight>
{{Out}}
<pre>(Police, Sanitation, Fire)
Line 2,476 ⟶ 2,696:
Or, more generally, by composition of generic functions:
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
"use strict";
 
Line 2,526 ⟶ 2,746:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>(Police, Sanitation, Fire)
Line 2,563 ⟶ 2,783:
 
'''Nested for-loop'''
<langsyntaxhighlight lang="jq">def check(fire; police; sanitation):
(fire != police) and (fire != sanitation) and (police != sanitation)
and (fire + police + sanitation == 12)
Line 2,572 ⟶ 2,792:
| range(1;8) as $sanitation
| select( check($fire; $police; $sanitation) )
| {$fire, $police, $sanitation}</langsyntaxhighlight>
 
'''In Brief'''
<langsyntaxhighlight lang="jq">{fire: range(1;8), police: range(1;8), sanitation: range(1;8)}
| select( .fire != .police and .fire != .sanitation and .police != .sanitation
and .fire + .police + .sanitation == 12
and .police % 2 == 0 )</langsyntaxhighlight>
 
'''combinations'''
<syntaxhighlight lang="jq">
<lang jq>
[range(1;8)]
| combinations(3)
| select( add == 12 and .[1] % 2 == 0)
| {fire: .[0], police: .[1], sanitation: .[2]}</langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Printf
 
function findsolution(rng=1:7)
Line 2,609 ⟶ 2,829:
 
printsolutions(findsolution())
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,630 ⟶ 2,850:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun main(args: Array<String>) {
Line 2,648 ⟶ 2,868:
}
println("\n$count valid combinations")
}</langsyntaxhighlight>
 
{{out}}
Line 2,673 ⟶ 2,893:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">
print( "Fire", "Police", "Sanitation" )
sol = 0
Line 2,686 ⟶ 2,906:
end
print( string.format( "\n%d solutions found", sol ) )
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,709 ⟶ 2,929:
 
=={{header|MAD}}==
<langsyntaxhighlight MADlang="mad"> NORMAL MODE IS INTEGER
PRINT COMMENT $ POLICE SANITATION FIRE$
THROUGH LOOP, FOR P=2, 2, P.G.7
Line 2,718 ⟶ 2,938:
LOOP CONTINUE
VECTOR VALUES OCC = $I6,S2,I10,S2,I4*$
END OF PROGRAM</langsyntaxhighlight>
{{out}}
<pre>POLICE SANITATION FIRE
Line 2,737 ⟶ 2,957:
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">#determines if i, j, k are exclusive numbers
exclusive_numbers := proc(i, j, k)
if (i = j) or (i = k) or (j = k) then
Line 2,760 ⟶ 2,980:
 
department_numbers();
</syntaxhighlight>
</lang>
{{out|Output}}
<pre>
Line 2,781 ⟶ 3,001:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Select[Permutations[Range[7], {3}], Total[#] == 12 && EvenQ[First[#]] &]</langsyntaxhighlight>
{{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}}==
<langsyntaxhighlight lang="modula2">MODULE DepartmentNumbers;
FROM Conversions IMPORT IntToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 2,831 ⟶ 3,135:
 
ReadChar;
END DepartmentNumbers.</langsyntaxhighlight>
 
=={{header|Mercury}}==
<langsyntaxhighlight lang="mercury">:- module department_numbers.
:- interface.
 
Line 2,862 ⟶ 3,166:
Police \= Fire,
Sanitation \= Fire,
Police + Sanitation + Fire = 12.</langsyntaxhighlight>
{{out}}
<pre>P S F
Line 2,881 ⟶ 3,185:
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">type Solution = tuple[p, s, f: int]
 
iterator solutions(max, total: Positive): Solution =
Line 2,893 ⟶ 3,197:
echo "P S F"
for sol in solutions(7, 12):
echo sol.p, " ", sol.s, " ", sol.f</langsyntaxhighlight>
 
{{out}}
Line 2,914 ⟶ 3,218:
=={{header|Objeck}}==
{{Trans|C++}}
<langsyntaxhighlight lang="objeck">class Program {
function : Main(args : String[]) ~ Nil {
sol := 1;
Line 2,929 ⟶ 3,233:
};
}
}</langsyntaxhighlight>
 
Output:
Line 2,951 ⟶ 3,255:
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">(*
<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 3,016 ⟶ 3,320:
print_sfp_list result;
 
</syntaxhighlight>
</lang>
{{out}}
<pre>S F P
Line 3,037 ⟶ 3,341:
=={{header|PARI/GP}}==
 
<langsyntaxhighlight lang="parigp">forstep(p=2,6,2, for(f=1,7, s=12-p-f; if(p!=f && p!=s && f!=s && s>0 && s<8, print(p" "f" "s))))</langsyntaxhighlight>
{{out}}
<pre>2 3 7
Line 3,056 ⟶ 3,360:
=={{header|Perl}}==
 
<syntaxhighlight lang="perl">
<lang Perl>
#!/usr/bin/perl
 
Line 3,087 ⟶ 3,391:
}
}
</syntaxhighlight>
</lang>
 
 
Above Code cleaned up and shortened
 
<syntaxhighlight lang="perl">
<lang Perl>
#!/usr/bin/perl
 
Line 3,112 ⟶ 3,416:
}
}
</syntaxhighlight>
</lang>
 
Output:
<syntaxhighlight lang="perl">
<lang Perl>
Police - Fire - Sanitation
2 - 3 - 7
Line 3,131 ⟶ 3,435:
6 - 4 - 2
6 - 5 - 1
</syntaxhighlight>
</lang>
===Alternate with Regex===
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Department_numbers
Line 3,143 ⟶ 3,447:
/(.).* \s .*?(?!\1)(.).* \s .*(?!\1)(?!\2)(.)
(??{$1+$2+$3!=12})
(?{ print "@{^CAPTURE}\n" })(*FAIL)/x;</langsyntaxhighlight>
{{out}}
<pre>
Line 3,164 ⟶ 3,468:
</pre>
===Alternate with Glob===
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # https://rosettacode.org/wiki/Department_numbers
Line 3,173 ⟶ 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;</langsyntaxhighlight>
Output same as with Regex
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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 3,196 ⟶ 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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,221 ⟶ 3,525:
=={{header|PHP}}==
 
<langsyntaxhighlight PHPlang="php"><?php
 
$valid = 0;
Line 3,233 ⟶ 3,537:
}
}
echo $valid, ' valid combinations found.', PHP_EOL;</langsyntaxhighlight>
 
{{out}}
Line 3,255 ⟶ 3,559:
 
===Constraint model===
<langsyntaxhighlight Picatlang="picat">import cp.
 
go ?=>
Line 3,276 ⟶ 3,580:
Police + Sanitation + Fire #= 12,
Police mod 2 #= 0,
solve([Police,Sanitation,Fire]).</langsyntaxhighlight>
 
{{out}}
Line 3,298 ⟶ 3,602:
 
===Loop===
<langsyntaxhighlight Picatlang="picat">go2 => department_numbers2(N) =>
println(" P S F"),
foreach(P in 1..N, P mod 2 == 0)
Line 3,306 ⟶ 3,610:
end
end
end.</langsyntaxhighlight>
 
===List comprehension===
<langsyntaxhighlight Picatlang="picat">import util.
 
department_numbers3(N) =>
Line 3,317 ⟶ 3,621:
F in 1..N,
F != P, F != S, P + S + F == 12],
println(map(L,join).join("\n")).</langsyntaxhighlight>
 
===Prolog style===
{{trans|Prolog}}
<langsyntaxhighlight Picatlang="picat">go :-
println("P F S"),
assign(Police, Fire, Sanitation),
Line 3,337 ⟶ 3,641:
police(A), fire(B), san(C),
A != B, A != C, B != C,
12 is A + B + C.</langsyntaxhighlight>
 
 
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de numbers NIL
(co 'numbers
(let N 7
Line 3,359 ⟶ 3,663:
(<> 12 (apply + L))
(println L) ) ) ) )
(departments)</langsyntaxhighlight>
{{out}}
<pre>
Line 3,379 ⟶ 3,683:
 
===Pilog===
<langsyntaxhighlight PicoLisplang="picolisp">(be departments (@Pol @Fire @San)
(member @Pol (2 4 6))
(for @Fire 1 7)
Line 3,388 ⟶ 3,692:
(^ @
(= 12
(+ (-> @Pol) (-> @Fire) (-> @San)) ) ) )</langsyntaxhighlight>
{{out}}
<pre>
Line 3,410 ⟶ 3,714:
 
=={{header|Prolog}}==
<langsyntaxhighlight lang="prolog">
dept(X) :- between(1, 7, X).
 
Line 3,428 ⟶ 3,732:
 
?- main.
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,446 ⟶ 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===
<langsyntaxhighlight lang="python">from itertools import permutations
def solve():
Line 3,462 ⟶ 3,838:
if __name__ == '__main__':
solve()</langsyntaxhighlight>
 
{{out}}
Line 3,484 ⟶ 3,860:
Expressing the options directly and declaratively in terms of a ''bind'' operator, without importing ''permutations'':
{{Works with|Python|3}}
<langsyntaxhighlight lang="python">'''Department numbers'''
 
from itertools import (chain)
Line 3,553 ⟶ 3,929:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>('Police', 'Sanitation', 'Fire')
Line 3,577 ⟶ 3,953:
Nested ''bind'' (or ''concatMap'') expressions (like those above) can also be translated into list comprehension notation:
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Department numbers'''
 
from operator import ne
Line 3,653 ⟶ 4,029:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>('Police', 'Sanitation', 'Fire')
Line 3,674 ⟶ 4,050:
 
===Adapted from C# Example===
<langsyntaxhighlight lang="python">
# We start with the Police Department.
# Range is the start, stop, and step. This returns only even numbers.
Line 3,690 ⟶ 4,066:
print("Police: ", p, " Sanitation:", f, " Fire: ", s)
 
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,708 ⟶ 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,713 ⟶ 4,126:
{{trans|Forth}}
 
<langsyntaxhighlight Quackerylang="quackery"> [ 2dup = iff
[ 2drop drop ] done
dip over swap over = iff
Line 3,738 ⟶ 4,151:
witheach police ] is departments ( --> )
 
departments</langsyntaxhighlight>
 
{{out}}
Line 3,759 ⟶ 4,172:
=={{header|R}}==
We solve this task in two lines. The rest of the code is to make the result look nice.
<langsyntaxhighlight lang="rsplus">allPermutations <- setNames(expand.grid(seq(2, 7, by = 2), 1:7, 1:7), c("Police", "Sanitation", "Fire"))
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)</langsyntaxhighlight>
 
{{out}}
Line 3,786 ⟶ 4,199:
We filter the Cartesian product of the lists of candidate department numbers.
 
<langsyntaxhighlight lang="racket">#lang racket
(cons '(police fire sanitation)
(filter (λ (pfs) (and (not (check-duplicates pfs))
Line 3,792 ⟶ 4,205:
pfs))
(cartesian-product (range 2 8 2) (range 1 8) (range 1 8))))
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,814 ⟶ 4,227:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>for (1..7).combinations(3).grep(*.sum == 12) {
for .permutations\ .grep(*.[0] %% 2) {
say <police fire sanitation> Z=> .list;
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,840 ⟶ 4,253:
=={{header|REXX}}==
This REXX example essentially uses brute force approach for so simple a puzzle.
<langsyntaxhighlight lang="rexx">/*REXX program finds/displays all possible variants of (3) department numbering puzzle.*/
say 'police sanitation fire' /*display simple title for the output*/
say '══════ ══════════ ════' /* " head separator " " " */
Line 3,856 ⟶ 4,269:
say '══════ ══════════ ════' /* " head separator " " " */
say /*stick a fork in it, we're all done. */
say # ' solutions found.' /*also, show the # of solutions found. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 3,881 ⟶ 4,294:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
sanitation= 0
see "police fire sanitation" + nl
Line 3,899 ⟶ 4,312:
next
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,919 ⟶ 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}}==
<langsyntaxhighlight lang="ruby">
(1..7).to_a.permutation(3){|p| puts p.join if p.first.even? && p.sum == 12 }
</syntaxhighlight>
</lang>
{{Output}}
<pre>237
Line 3,942 ⟶ 4,380:
=={{header|Rust}}==
{{trans|C}}
<langsyntaxhighlight lang="rust">extern crate num_iter;
fn main() {
println!("Police Sanitation Fire");
Line 3,960 ⟶ 4,398:
}
}
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">val depts = {
(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,973 ⟶ 4,411:
println( depts.mkString("\n") )
}
</syntaxhighlight>
</lang>
{{output}}
<pre>(Police, Sanitation, Fire)
Line 3,994 ⟶ 4,432:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">@(1..7)->combinations(3, {|*a|
a.sum == 12 || next
a.permutations {|*b|
Line 4,000 ⟶ 4,438:
say (%w(police fire sanitation) ~Z b -> join(" "))
}
})</langsyntaxhighlight>
{{out}}
<pre>
Line 4,023 ⟶ 4,461:
Functional approach:
 
<langsyntaxhighlight lang="swift">let res = [2, 4, 6].map({x in
return (1...7)
.filter({ $0 != x })
Line 4,039 ⟶ 4,477:
for result in res {
print(result)
}</langsyntaxhighlight>
 
Iterative approach:
 
<langsyntaxhighlight lang="swift">var res = [(Int, Int, Int)]()
 
for x in [2, 4, 6] {
Line 4,059 ⟶ 4,497:
for result in res {
print(result)
}</langsyntaxhighlight>
 
{{out}}
Line 4,082 ⟶ 4,520:
 
<b>VERSION A</b> - using procedures and list operations
<langsyntaxhighlight lang="tcl">
# Procedure named ".." returns list of integers from 1 to max.
proc .. max {
Line 4,137 ⟶ 4,575:
}
puts "$valid valid combinations found."
</syntaxhighlight>
</lang>
 
<b>VERSION B</b> - using simple for loops with number literals
<langsyntaxhighlight lang="tcl">
set valid 0
for {set police 2} {$police <= 6} {incr police 2} {
Line 4,154 ⟶ 4,592:
}
puts "$valid valid combinations found."
</syntaxhighlight>
</lang>
 
<b>VERSION C</b> - using simple for loops with number variables
<langsyntaxhighlight lang="tcl">
set min 1
set max 7
Line 4,175 ⟶ 4,613:
 
puts "$valid valid combinations found."
</syntaxhighlight>
</lang>
 
<b>VERSION D</b> - using list filter with lambda expressions
<langsyntaxhighlight lang="tcl">
# Procedure named ".." returns list of integers from 1 to max.
proc .. max {
Line 4,231 ⟶ 4,669:
puts [join $numbersOk \n]
puts "[llength $numbersOk] valid combinations found."
</syntaxhighlight>
</lang>
{{output}}
All four versions (A, B, C and D) produce the same result:
Line 4,253 ⟶ 4,691:
 
=={{header|Tiny BASIC}}==
<langsyntaxhighlight lang="tinybasic"> PRINT "Police Sanitation Fire"
PRINT "------|----------|----"
10 LET P = P + 2
Line 4,266 ⟶ 4,704:
IF F < 7 THEN GOTO 30
IF S < 7 THEN GOTO 20
IF P < 6 THEN GOTO 10</langsyntaxhighlight>
 
=={{header|Transd}}==
<langsyntaxhighlight lang="scheme">#lang transd
 
MainModule : {
Line 4,279 ⟶ 4,717:
(if (eq (+ i j k) 12) (lout i " " j " " k)))))
)
}</langsyntaxhighlight>{{out}}
<pre>
Police | Sanit. | Fire
Line 4,301 ⟶ 4,739:
== {{header|TypeScript}} ==
{{trans|Sinclair ZX81 BASIC}}
<langsyntaxhighlight lang="javascript">
// Department numbers
console.log(`POLICE SANITATION FIRE`);
Line 4,314 ⟶ 4,752:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,333 ⟶ 4,771:
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#}}
<langsyntaxhighlight lang="vbnet">Module Module1
 
Sub Main()
Line 4,357 ⟶ 4,840:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>Police:2, Sanitation:3, Fire:7
Line 4,374 ⟶ 4,857:
Police:6, Sanitation:4, Fire:2</pre>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<langsyntaxhighlight lang="go">fn main() {
println("Police Sanitation Fire")
println("------ ---------- ----")
Line 4,392 ⟶ 4,875:
}
println("\n$count valid combinations")
}</langsyntaxhighlight>
 
{{out}}
Line 4,417 ⟶ 4,900:
 
=={{header|VTL-2}}==
<langsyntaxhighlight VTL2lang="vtl2">10 P=2
20 S=1
30 F=1
Line 4,432 ⟶ 4,915:
140 #=S<8*30
150 P=P+2
160 #=P<8*20</langsyntaxhighlight>
{{out}}
<pre>2 3 7
Line 4,451 ⟶ 4,934:
=={{header|Wren}}==
{{trans|Kotlin}}
<langsyntaxhighlight ecmascriptlang="wren">System.print("Police Sanitation Fire")
System.print("------ ---------- ----")
var count = 0
Line 4,467 ⟶ 4,950:
}
}
System.print("\n%(count) valid combinations")</langsyntaxhighlight>
 
{{out}}
Line 4,494 ⟶ 4,977:
{{trans|Sinclair ZX81 BASIC}}
{{works with|EXPL-32}}
<langsyntaxhighlight lang="xpl0">
\Department numbers
code CrLf=9, IntIn=10, IntOut=11, Text=12;
Line 4,520 ⟶ 5,003:
end;
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,539 ⟶ 5,022:
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}}==
<langsyntaxhighlight lang="zkl">Utils.Helpers.pickNFrom(3,[1..7].walk()) // 35 combos
.filter(fcn(numbers){ numbers.sum(0)==12 }) // which all sum to 12 (==5)
.println();</langsyntaxhighlight>
{{output}}
<pre>
Line 4,553 ⟶ 5,149:
 
For a table with repeated solutions using nested loops:
<langsyntaxhighlight lang="zkl">println("Police Fire Sanitation");
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) }</langsyntaxhighlight>
{{out}}
<pre>
3,021

edits