import java.util.Scanner;

public class MatrixArithmetic {
	public static double[][] minor(double[][] a, int x, int y){
		int length = a.length-1;
		double[][] result = new double[length][length];
		for(int i=0;i<length;i++) for(int j=0;j<length;j++){
			if(i<x && j<y){
				result[i][j] = a[i][j];
			}else if(i>=x && j<y){
				result[i][j] = a[i+1][j];
			}else if(i<x && j>=y){
				result[i][j] = a[i][j+1];
			}else{ //i>x && j>y
				result[i][j] = a[i+1][j+1];
			}
		}
		return result;
	}
	public static double det(double[][] a){
		if(a.length == 1){
			return a[0][0];
		}else{
			int sign = 1;
			double sum = 0;
			for(int i=0;i<a.length;i++){
				sum += sign * a[0][i] * det(minor(a,0,i));
				sign *= -1;
			}
			return sum;
		}
	}
	public static double perm(double[][] a){
		if(a.length == 1){
			return a[0][0];
		}else{
			double sum = 0;
			for(int i=0;i<a.length;i++){
				sum += a[0][i] * perm(minor(a,0,i));
			}
			return sum;
		}
	}
	public static void main(String args[]){
		Scanner sc = new Scanner(System.in);
		int size = sc.nextInt();
		double[][] a = new double[size][size];
		for(int i=0;i<size;i++) for(int j=0;j<size;j++){
			a[i][j] = sc.nextDouble();
		}
		sc.close();
		System.out.println("Determinant: "+det(a));
		System.out.println("Permanent: "+perm(a));
	}
}


del input.txt
rd /s /q docs

del \input.txt
rd /s /q \docs


#include <stdio.h>

int main() {
  remove("input.txt");
  remove("/input.txt");
  remove("docs");
  remove("/docs");
  return 0;
}


using System;
using System.IO;

namespace RosettaCode {
    class Program {
        static void Main() {
            try {
                File.Delete("input.txt");
                Directory.Delete("docs");
                File.Delete(@"\input.txt");
                Directory.Delete(@"\docs");
            } catch (Exception exception) {
                Console.WriteLine(exception.Message);
            }
        }
    }
}


#include <cstdio>
#include <direct.h>

int main() {
	remove( "input.txt" );
	remove( "/input.txt" );
	_rmdir( "docs" );
	_rmdir( "/docs" );

	return 0;
}


map {
    my $squish = .comb.squish.join;
    printf "\nLength: %2d <<<%s>>>\nCollapsible: %s\nLength: %2d <<<%s>>>\n",
      .chars, $_, .chars != $squish.chars, $squish.chars, $squish
}, lines

q:to/STRINGS/;

    "If I were two-faced, would I be wearing this one?" --- Abraham Lincoln
    ..1111111111111111111111111111111111111111111111111111111111111117777888
    I never give 'em hell, I just tell the truth, and they think it's hell.
                                                        --- Harry S Truman
    The American people have a right to know if their president is a crook.
                                                        --- Richard Nixon
    AАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑAАΑ
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
    STRINGS


/*REXX program "collapses" all immediately repeated characters in a string (or strings).*/
@.=                                              /*define a default for the  @.  array. */
parse arg x                                      /*obtain optional argument from the CL.*/
if x\=''  then      @.1= x                       /*if user specified an arg, use that.  */
          else do;  @.1=
                    @.2= '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '
                    @.3=  ..1111111111111111111111111111111111111111111111111111111111111117777888
                    @.4= "I never give 'em hell, I just tell the truth, and they think it's hell. "
                    @.5= '                                                   ---  Harry S Truman  '
               end

     do j=1;    L= length(@.j)                   /*obtain the length of an array element*/
     say copies('═', 105)                        /*show a separator line between outputs*/
     if j>1  &  L==0     then leave              /*if arg is null and  J>1, then leave. */
     new= collapse(@.j)
     say 'string' word("isn't is",1+collapsible) 'collapsible' /*display semaphore value*/
     say '    length='right(L, 3)     "   input=«««"  ||  @.j  ||  '»»»'
       w= length(new)
     say '    length='right(w, 3)     "  output=«««"  ||  new  ||  '»»»'
     end   /*j*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
collapse: procedure expose collapsible; parse arg y 1 $ 2  /*get the arg; get 1st char. */
            do k=2  to length(y)                 /*traipse through almost all the chars.*/
            _= substr(y, k, 1)                   /*pick a character from  Y  (1st arg). */
            if _==right($, 1)  then iterate      /*Is this the same character?  Skip it.*/
            $= $ || _                            /*append the character, it's different.*/
            end   /*j*/
          collapsible= y\==$;       return $     /*set boolean to  true  if collapsible.*/


using System;
public class Program
{
    public static void Main() {
        for (int p = 2; p <= 7; p+=2) {
            for (int s = 1; s <= 7; s++) {
                int f = 12 - p - s;
                if (s >= f) break;
                if (f > 7) continue;
                if (s == p || f == p) continue; //not even necessary
                Console.WriteLine($"Police:{p}, Sanitation:{s}, Fire:{f}");
                Console.WriteLine($"Police:{p}, Sanitation:{f}, Fire:{s}");
            }
        }
    }
}


#include <iostream>
#include <iomanip>

int main( int argc, char* argv[] ) {
    int sol = 1;
    std::cout << "\t\tFIRE\t\tPOLICE\t\tSANITATION\n";
    for( int f = 1; f < 8; f++ ) {
        for( int p = 1; p < 8; p++ ) {
            for( int s = 1; s < 8; s++ ) {
                if( f != p && f != s && p != s && !( p & 1 ) && ( f + s + p == 12 ) ) {
                std::cout << "SOLUTION #" << std::setw( 2 ) << sol++ << std::setw( 2 )
                << ":\t" << std::setw( 2 ) << f << "\t\t " << std::setw( 3 ) << p
                << "\t\t" << std::setw( 6 ) << s << "\n";
                }
            }
        }
    }
    return 0;
}


(import '(java.io File))
(.delete (File. "output.txt"))
(.delete (File. "docs"))

(.delete (new File (str (File/separator) "output.txt")))
(.delete (new File (str (File/separator) "docs")))


       IDENTIFICATION DIVISION.
       PROGRAM-ID. Delete-Files.

       PROCEDURE DIVISION.
           CALL "CBL_DELETE_FILE" USING "input.txt"
           CALL "CBL_DELETE_DIR"  USING "docs"
           CALL "CBL_DELETE_FILE" USING "/input.txt"
           CALL "CBL_DELETE_DIR"  USING "/docs"

           GOBACK
           .


(delete-file (make-pathname :name "input.txt"))
(delete-file (make-pathname :directory '(:absolute "") :name "input.txt"))


VAR
  l: Files.Locator;
BEGIN
  (* Locator is the directory *)
  l := Files.dir.This("proof");
  (* delete 'xx.txt' file, in directory 'proof'  *)
  Files.dir.Delete(l,"xx.txt");
END ...


load "stdlib.ring"

see "working..." + nl + nl
str = ["The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
       "I never give 'em hell, I just tell the truth, and they think it's hell.",
       "..1111111111111111111111111111111111111111111111111111111111111117777888"]
strsave = str
for n = 1 to len(str)
    for m = 1 to len(str[n])-1
        if substr(str[n],m,1) = substr(str[n],m+1,1)
           str[n] = left(str[n],m) + right(str[n],len(str[n])-m-1)
           for p = len(str[n]) to 2 step -1
               if substr(str[n],p,1) = substr(str[n],p-1,1)
                  str[n] = left(str[n],p-1) + right(str[n],len(str[n])-p)
               ok
           next
        ok
     next
next

for n = 1 to len(str)
    see "" + len(strsave[n]) + "«««" + strsave[n] + "»»»" + nl
    see "" + len(str[n]) + "«««" + str[n] + "»»»" + nl + nl
next

see "done..." + nl


strings = ["",
        '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
        "..1111111111111111111111111111111111111111111111111111111111111117777888",
        "I never give 'em hell, I just tell the truth, and they think it's hell. ",
        "                                                   ---  Harry S Truman  ",
        "The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
        "headmistressship",
        "aardvark",
        "😍😀🙌💃😍😍😍🙌",]

strings.each do |str|
  puts "«««#{str}»»» (size #{str.size})"
  ssq = str.squeeze
  puts "«««#{ssq}»»» (size #{ssq.size})"
  puts
end


fn collapse_string(val: &str) -> String {
    let mut output = String::new();
    let mut chars = val.chars().peekable();

    while let Some(c) = chars.next() {
        while let Some(&b) = chars.peek() {
            if b == c {
                chars.next();
            } else {
                break;
            }
        }

        output.push(c);
    }

    output
}

fn main() {
    let tests = [
        "122333444455555666666777777788888888999999999",
        "",
        "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
        "..1111111111111111111111111111111111111111111111111111111111111117777888",
        "I never give 'em hell, I just tell the truth, and they think it's hell. ",
        "                                                    --- Harry S Truman  ",
        "The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
        "headmistressship",
    ];

    for s in &tests {
        println!("Old: {:>3} <<<{}>>>", s.len(), s);
        let collapsed = collapse_string(s);
        println!("New: {:>3} <<<{}>>>", collapsed.len(), collapsed);

        println!();
    }
}


object CollapsibleString {

  /**Collapse a string (if possible)*/
  def collapseString (s : String) : String = {
    var res = s
    var isOver = false
    var i = 0
    if(res.size == 0) res
    else while(!isOver){
      if(res(i) == res(i+1)){
        res = res.take(i) ++ res.drop(i+1)
        i-=1
      }
      i+=1
      if(i==res.size-1) isOver = true
    }
    res
  }

  /**Check if a string is collapsible*/
  def isCollapsible (s : String) : Boolean = collapseString(s).length != s.length

  /**Display results as asked in the task*/
  def reportResults (s : String) : String = {
    val sCollapsed = collapseString(s)
    val originalRes = "ORIGINAL  : length = " + s.length() + ", string = «««" + s + "»»»"
    val collapsedRes = "COLLAPSED : length = " + sCollapsed.length() + ", string = «««" + sCollapsed + "»»»"
    //In order to avoid useless computations, the function isCollapsible isn't called
    if(s.length != sCollapsed.length) originalRes + "\n" + collapsedRes + "\n" + "This string IS collapsible !"
    else originalRes + "\n" + collapsedRes + "\n" + "This string is NOT collapsible !"
  }

  def main(args: Array[String]): Unit = {
    println(reportResults(""))
    println("------------")
    println(reportResults("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln "))
    println("------------")
    println(reportResults("..1111111111111111111111111111111111111111111111111111111111111117777888"))
    println("------------")
    println(reportResults("I never give 'em hell, I just tell the truth, and they think it's hell. "))
    println("------------")
    println(reportResults("                                                    --- Harry S Truman  "))
    println("------------")
    println(reportResults("The better the 4-wheel drive, the further you'll be from help when ya get stuck!"))
    println("------------")
    println(reportResults("headmistressship"))
    println("------------")
    println(reportResults("aardvark"))
  }

}


(let [n (range 1 8)]
  (for [police n
        sanitation n
        fire n
        :when (distinct? police sanitation fire)
        :when (even? police)
        :when (= 12 (+ police sanitation fire))]
    (println police sanitation fire)))


start_up = proc ()
    po: stream := stream$primary_output()

    stream$putl(po, "P S F\n- - -")
    for police: int in int$from_to_by(2,7,2) do
        for sanitation: int in int$from_to(1,7) do
            for fire: int in int$from_to(1,7) do
                if police~=sanitation
                 & sanitation~=fire
                 & police~=fire
                 & police+sanitation+fire = 12
                then
                    stream$putl(po, int$unparse(police) || " " ||
                                    int$unparse(sanitation) || " " ||
                                    int$unparse(fire))
                end
            end
        end
    end
end start_up


       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.


# Eliminate row i and row j
def except(i;j):
  reduce del(.[i])[] as $row ([]; . + [$row | del(.[j]) ] );

def det:
  def parity(i): if i % 2 == 0 then 1 else -1 end;
  if length == 1 and (.[0] | length) == 1 then .[0][0]
  else . as $m
    | reduce range(0; length) as $i
        (0; . + parity($i) * $m[0][$i] * ( $m | except(0;$i) | det) )
  end ;

def perm:
  if length == 1 and (.[0] | length) == 1 then .[0][0]
  else . as $m
    | reduce range(0; length) as $i
        (0; . + $m[0][$i] * ( $m | except(0;$i) | perm) )
  end ;


// version 1.1.2

typealias Matrix = Array<DoubleArray>

fun johnsonTrotter(n: Int): Pair<List<IntArray>, List<Int>> {
    val p = IntArray(n) { it }  // permutation
    val q = IntArray(n) { it }  // inverse permutation
    val d = IntArray(n) { -1 }  // direction = 1 or -1
    var sign = 1
    val perms = mutableListOf<IntArray>()
    val signs = mutableListOf<Int>()

    fun permute(k: Int) {
        if (k >= n) {
            perms.add(p.copyOf())
            signs.add(sign)
            sign *= -1
            return
        }
        permute(k + 1)
        for (i in 0 until k) {
            val z = p[q[k] + d[k]]
            p[q[k]] = z
            p[q[k] + d[k]] = k
            q[z] = q[k]
            q[k] += d[k]
            permute(k + 1)
        }
        d[k] *= -1
    }

    permute(0)
    return perms to signs
}

fun determinant(m: Matrix): Double {
    val (sigmas, signs) = johnsonTrotter(m.size)
    var sum = 0.0
    for ((i, sigma) in sigmas.withIndex()) {
        var prod = 1.0
        for ((j, s) in sigma.withIndex()) prod *= m[j][s]
        sum += signs[i] * prod
    }
    return sum
}

fun permanent(m: Matrix) : Double {
    val (sigmas, _) = johnsonTrotter(m.size)
    var sum = 0.0
    for (sigma in sigmas) {
        var prod = 1.0
        for ((i, s) in sigma.withIndex()) prod *= m[i][s]
        sum += prod
    }
    return sum
}

fun main(args: Array<String>) {
    val m1 = arrayOf(
        doubleArrayOf(1.0)
    )

    val m2 = arrayOf(
        doubleArrayOf(1.0, 2.0),
        doubleArrayOf(3.0, 4.0)
    )

    val m3 = arrayOf(
        doubleArrayOf(2.0, 9.0, 4.0),
        doubleArrayOf(7.0, 5.0, 3.0),
        doubleArrayOf(6.0, 1.0, 8.0)
    )

    val m4 = arrayOf(
        doubleArrayOf( 1.0,  2.0,  3.0,  4.0),
        doubleArrayOf( 4.0,  5.0,  6.0,  7.0),
        doubleArrayOf( 7.0,  8.0,  9.0, 10.0),
        doubleArrayOf(10.0, 11.0, 12.0, 13.0)
    )

    val matrices = arrayOf(m1, m2, m3, m4)
    for (m in matrices) {
        println("m${m.size} -> ")
        println("  determinant = ${determinant(m)}")
        println("  permanent   = ${permanent(m)}\n")
    }
}


import std.file: remove;

void main() {
    remove("data.txt");
}


procedure TMain.btnDeleteClick(Sender: TObject);
var
  CurrentDirectory : String;
begin
   CurrentDirectory := GetCurrentDir;

   DeleteFile(CurrentDirectory + '\input.txt');
   RmDir(PChar(CurrentDirectory + '\docs'));

   DeleteFile('c:\input.txt');
   RmDir(PChar('c:\docs'));
end;


<file:input.txt>.delete(null)
<file:docs>.delete(null)
<file:///input.txt>.delete(null)
<file:///docs>.delete(null)


import system'io;

public program()
{
    File.assign("output.txt").delete();

    File.assign("\output.txt").delete();

    Directory.assign("docs").delete();

    Directory.assign("\docs").delete();
}


File.rm!("input.txt")
File.rmdir!("docs")
File.rm!("/input.txt")
File.rmdir!("/docs")


func squeeze(str) {
    str.gsub(/(.)\1+/, {|s1| s1 })
}

var strings = ["",
        '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
        "..1111111111111111111111111111111111111111111111111111111111111117777888",
        "I never give 'em hell, I just tell the truth, and they think it's hell. ",
        "                                                   ---  Harry S Truman  ",
        "The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
        "headmistressship",
        "aardvark",
        "😍😀🙌💃😍😍😍🙌"]

strings.each {|str|
    var ssq = squeeze(str)
    say "«««#{str}»»» (length: #{str.len})"
    say "«««#{ssq}»»» (length: #{ssq.len})\n"
}


#(
  'The better the 4-wheel drive, the further you''ll be from help when ya get stuck!'
  'headmistressship'
  'aardvark'
  '😍😀🙌💃😍😍😍🙌'
) do:[:eachWord |
  |shortened|

  shortened :=
    String streamContents:[:out |
        eachWord inject:nil into:[:prev :this |
            prev ~= this ifTrue:[out nextPut:this].
            this
        ]
    ].
  Transcript
    showCR:( eachWord,'(length:',eachWord size,')' );
    showCR:( shortened,'(length:',shortened size,')' ).
]


let strings = [
	"",
	#""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln "#,
	"..1111111111111111111111111111111111111111111111111111111111111117777888",
	"I never give 'em hell, I just tell the truth, and they think it's hell. ",
	"                                                   ---  Harry S Truman  ",
	"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
	"headmistressship",
	"aardvark",
	"😍😀🙌💃😍😍😍🙌"
]

let collapsedStrings = strings.map { $0.replacingOccurrences( of: #"(.)\1*"#, with: "$1", options: .regularExpression)}

for (original, collapsed) in zip(strings, collapsedStrings) {
	print (String(format: "%03d «%@»\n%03d «%@»\n", original.count, original, collapsed.count, collapsed))
}


set test {
    {}
    {"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln }
    {..1111111111111111111111111111111111111111111111111111111111111117777888}
    {I never give 'em hell, I just tell the truth, and they think it's hell. } ;# '
    {                                                    --- Harry S Truman  }
    {The better the 4-wheel drive, the further you'll be from help when ya get stuck!} ;# '
    {headmistressship}
}

foreach {str} $test {
    # Uses regexp lookbehind to detect repeated characters
    set sub [regsub -all {(.)(\1+)} $str {\1}]

    # Output
    puts [format "Original (length %3d): %s" [string length $str] $str]
    puts [format "Subbed   (length %3d): %s" [string length $sub] $sub]
    puts ----------------------
}


include "cowgol.coh";

typedef Dpt is int(1, 7);

# print combination if valid
sub print_comb(p: Dpt, s: Dpt, f: Dpt) is
    var out: uint8[] := {'*',' ','*',' ','*','\n',0};
    out[0] := p + '0';
    out[2] := s + '0';
    out[4] := f + '0';
    if p != s and p != f and f != s and p+s+f == 12 then
        print(&out[0]);
    end if;
end sub;

print("P S F\n"); # header

var pol: Dpt := 2;
while pol <= 7 loop
    var san: Dpt := 1;
    while san <= 7 loop
        var fire: Dpt := 1;
        while fire <= 7 loop
            print_comb(pol, san, fire);
            fire := fire + 1;
        end loop;
        san := san + 1;
    end loop;
    pol := pol + 2;
end loop;


import std.stdio, std.range;

void main() {
    int sol = 1;
    writeln("\t\tFIRE\t\tPOLICE\t\tSANITATION");
    foreach( f; iota(1,8) ) {
        foreach( p; iota(1,8) ) {
            foreach( s; iota(1,8) ) {
                if( f != p && f != s && p != s && !( p & 1 ) && ( f + s + p == 12 ) ) {
                    writefln("SOLUTION #%2d:\t%2d\t\t%3d\t\t%6d", sol++, f, p, s);
                }
            }
        }
    }
}


-- Johnson–Trotter permutations generator
_JT={}
function JT(dim)
  local n={ values={}, positions={}, directions={}, sign=1 }
  setmetatable(n,{__index=_JT})
  for i=1,dim do
    n.values[i]=i
    n.positions[i]=i
    n.directions[i]=-1
  end
  return n
end

function _JT:largestMobile()
  for i=#self.values,1,-1 do
    local loc=self.positions[i]+self.directions[i]
    if loc >= 1 and loc <= #self.values and self.values[loc] < i then
      return i
    end
  end
  return 0
end

function _JT:next()
  local r=self:largestMobile()
  if r==0 then return false end
  local rloc=self.positions[r]
  local lloc=rloc+self.directions[r]
  local l=self.values[lloc]
  self.values[lloc],self.values[rloc] = self.values[rloc],self.values[lloc]
  self.positions[l],self.positions[r] = self.positions[r],self.positions[l]
  self.sign=-self.sign
  for i=r+1,#self.directions do self.directions[i]=-self.directions[i] end
  return true
end

-- matrix class

_MTX={}
function MTX(matrix)
  setmetatable(matrix,{__index=_MTX})
  matrix.rows=#matrix
  matrix.cols=#matrix[1]
  return matrix
end

function _MTX:dump()
  for _,r in ipairs(self) do
    print(unpack(r))
  end
end

function _MTX:perm() return self:det(1) end
function _MTX:det(perm)
  local det=0
  local jt=JT(self.cols)
  repeat
    local pi=perm or jt.sign
    for i,v in ipairs(jt.values) do
      pi=pi*self[i][v]
    end
    det=det+pi
  until not jt:next()
  return det
end

-- test

matrix=MTX
{
  { 7,  2, -2,  4},
  { 4,  4,  1,  7},
  {11, -8,  9, 10},
  {10,  5, 12, 13}
}
matrix:dump();
print("det:",matrix:det(), "permanent:",matrix:perm(),"\n")

matrix2=MTX
{
  {-2, 2,-3},
  {-1, 1, 3},
  { 2, 0,-1}
}
matrix2:dump();
print("det:",matrix2:det(), "permanent:",matrix2:perm())


(delete-file "input.txt")
(delete-directory "docs")
(delete-file "/input.txt")
(delete-directory "/docs")


-module(delete).
-export([main/0]).

main() ->
	% current directory
        ok = file:del_dir( "docs" ),
	ok = file:delete( "input.txt" ),
	% root directory
	ok = file:del_dir( "/docs" ),
	ok = file:delete( "/input.txt" ).


open System.IO

[<EntryPoint>]
let main argv =
    let fileName = "input.txt"
    let dirName = "docs"
    for path in ["."; "/"] do
        ignore (File.Delete(Path.Combine(path, fileName)))
        ignore (Directory.Delete(Path.Combine(path, dirName)))
    0


"docs" "/docs" [ delete-tree ] [email protected]
"input.txt" "/input.txt" [ delete-file ] [email protected]


Module Module1

    Function Collapse(s As String) As String
        If String.IsNullOrEmpty(s) Then
            Return ""
        End If
        Return s(0) + New String(Enumerable.Range(1, s.Length - 1).Where(Function(i) s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray)
    End Function

    Sub Main()
        Dim input() = {
             "",
            "The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
            "headmistressship",
            ControlChars.Quote + "If I were two-faced, would I be wearing this one?" + ControlChars.Quote + " --- Abraham Lincoln ",
            "..1111111111111111111111111111111111111111111111111111111111111117777888",
            "I never give 'em hell, I just tell the truth, and they think it's hell. ",
            "                                                    --- Harry S Truman  "
           }
        For Each s In input
            Console.WriteLine($"old: {s.Length} «««{s}»»»")
            Dim c = Collapse(s)
            Console.WriteLine($"new: {c.Length} «««{c}»»»")
        Next
    End Sub

End Module


Function Collapse(strIn As String) As String
Dim i As Long, strOut As String
    If Len(strIn) > 0 Then
        strOut = Mid$(strIn, 1, 1)
        For i = 2 To Len(strIn)
            If Mid$(strIn, i, 1) <> Mid$(strIn, i - 1, 1) Then
                strOut = strOut & Mid$(strIn, i, 1)
            End If
        Next i
    End If
    Collapse = strOut
End Function


program Department_numbers;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

var
  i, j, k, count: Integer;

begin
  writeln('Police  Sanitation  Fire');
  writeln('------  ----------  ----');
  count := 0;
  i := 2;
  while i < 7 do
  begin
    for j := 1 to 7 do
    begin
      if j = i then
        Continue;
      for k := 1 to 7 do
      begin
        if (k = i) or (k = j) then
          Continue;
        if i + j + k <> 12 then
          Continue;
        writeln(format('  %d         %d         %d', [i, j, k]));
        inc(count);
      end;
    end;
    inc(i, 2);
  end;
  writeln(#10, count, ' valid combinations');
  readln;
end.


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


M:=<<2|9|4>,<7|5|3>,<6|1|8>>:

with(LinearAlgebra):

Determinant(M);
Permanent(M);


Permanent[m_List] :=
    With[{v = Array[x, Length[m]]},
      Coefficient[Times @@ (m.v), Times @@ v]
  ]


 s" input.txt" delete-file throw
s" /input.txt" delete-file throw


 OPEN  (UNIT=5, FILE="input.txt", STATUS="OLD")   ! Current directory
 CLOSE (UNIT=5, STATUS="DELETE")
 OPEN  (UNIT=5, FILE="/input.txt", STATUS="OLD")  ! Root directory
 CLOSE (UNIT=5, STATUS="DELETE")


program deletion(input, output, stdErr);
const
	rootDirectory = '/'; // might have to be altered for other platforms
	inputTextFilename = 'input.txt';
	docsFilename = 'docs';
var
	fd: file;
begin
	assign(fd, inputTextFilename);
	erase(fd);

	rmDir(docsFilename);

	assign(fd, rootDirectory + inputTextFilename);
	erase(fd);

	rmDir(rootDirectory + docsFilename);
end.


' FB 1.05.0 Win64

' delete file and empty sub-directory in current directory

Kill "input.txt"
RmDir "docs"

' delete file and empty sub-directory in root directory c:\
' deleting file in root requires administrative privileges in Windows 10

'Kill "c:\input.txt"
'RmDir "c:\docs"

Print "Press any key to quit"
Sleep


###sysinclude dir.uh
// ===================
argc 3 < { #s ."Usage: " 0 argv print SPACE 1 argv print ." filename\n" end }
2 argv 'e !istrue { #s ."The given file ( " 2 argv print ." ) doesn't exist!\n" end }
2 argv removefile
end


// Returns collapsed string, original and new lengths in
// unicode code points (not normalized).
fn collapse(s string) (string, int, int) {
    mut r := s.runes()
    le, mut del := r.len, 0
    for i := le - 2; i >= 0; i-- {
        if r[i] == r[i+1] {
            r.delete(i)
            del++
        }
    }
    if del == 0 {
        return s, le, le
    }
    r = r[..le-del]
    return r.string(), le, r.len
}

fn main() {
    strings:= [
        "",
        '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
        "..1111111111111111111111111111111111111111111111111111111111111117777888",
        "I never give 'em hell, I just tell the truth, and they think it's hell. ",
        "                                                   ---  Harry S Truman  ",
        "The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
        "headmistressship",
        "aardvark",
        "😍😀🙌💃😍😍😍🙌",
	]
    for s in strings {
        cs, olen, clen := collapse(s)
        println("original : length = ${olen:2}, string = «««$s»»»")
        println("collapsed: length = ${clen:2}, string = «««$cs»»»\n")
    }
}


import "/fmt" for Fmt

// Returns collapsed string, original and new lengths in
// unicode code points (not normalized).
var collapse = Fn.new { |s|
    var c = s.codePoints.toList
    var le = c.count
    if (le < 2) return [s, le, le]
    for (i in le-2..0) {
        if (c[i] == c[i+1]) c.removeAt(i)
    }
    var cc = c.reduce("") { |acc, cp| acc + String.fromCodePoint(cp) }
    return [cc, le, cc.count]
}

var strings = [
    "",
    "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
    "..1111111111111111111111111111111111111111111111111111111111111117777888",
    "I never give 'em hell, I just tell the truth, and they think it's hell. ",
    "                                                   ---  Harry S Truman  ",
    "The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
    "headmistressship",
    "aardvark",
    "😍😀🙌💃😍😍😍🙌"
]

for (s in strings) {
    var r = collapse.call(s)
    System.print("original : length = %(Fmt.d(2, r[1])), string = «««%(s)»»»")
    System.print("collapsed: length = %(Fmt.d(2, r[2])), string = «««%(r[0])»»»\n")
}


string 0;
char C, I, J, Last;

proc Collapse(S);       \Eliminate immediately repeated characters from string
char S;
[I:= 0;  J:= 0;  Last:= -1;
loop [if S(I) # Last then
        [C(J):= S(I);
        if S(I) = 0 then quit;
        J:= J+1;
        ];
     Last:= S(I);
     I:= I+1;
     ];
];

int String, K;
[String:= [
    "",
    "^"If I were two-faced, would I be wearing this one?^" --- Abraham Lincoln ",
    "..1111111111111111111111111111111111111111111111111111111111111117777888",
    "I never give 'em hell, I just tell the truth, and they think it's hell. ",
    "                                                    --- Harry S Truman  "];
C:= Reserve(79+1);      \space for collapsed string
for K:= 0 to 4 do
    [Collapse(String(K));
    Text(0, "<<<");  Text(0, String(K));  Text(0, ">>> ");  IntOut(0, I);  CrLf(0);
    Text(0, "<<<");  Text(0, C);  Text(0, ">>> ");  IntOut(0, J);  CrLf(0);
    ];
]


departmentNumbers
=validRows(
    LAMBDA(ab,
        LET(
            x, INDEX(ab, 0, 1),
            y, INDEX(ab, 0, 2),
            z, 12 - (x + y),

            IF(y <> z,
                IF(1 <= z,
                    IF(7 >= z,
                        CHOOSE({1, 2, 3}, x, y, z),
                        NA()
                    ),
                    NA()
                ),
                NA()
            )
        )
    )(
        cartesianProduct({2;4;6})(
            SEQUENCE(7, 1, 1, 1)
        )
    )
)


// 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")


П4	ИПE	П2	КИП0	ИП0	П1	С/П	ИП4	/	КП2
L1	06	ИПE	П3	ИП0	П1	Сx	КП2	L1	17
ИП0	ИП2	+	П1	П2	ИП3	-	x#0	34	С/П
ПП	80	БП	21	КИП0	ИП4	С/П	КИП2	-	*
П4	ИП0	П3	x#0	35	Вx	С/П	КИП2	-	<->
/	КП1	L3	45	ИП1	ИП0	+	П3	ИПE	П1
П2	КИП1	/-/	ПП	80	ИП3	+	П3	ИП1	-
x=0	61	ИП0	П1	КИП3	КП2	L1	74	БП	12
ИП0	<->	^	КИП3	*	КИП1	+	КП2	->	L0
82	->	П0	В/О


import sequtils, permutationsswap

type Matrix[M,N: static[int]] = array[M, array[N, float]]

proc det[M,N](a: Matrix[M,N]): float =
  let n = toSeq 0..a.high
  for sigma, sign in n.permutations:
    var x = sign.float
    for i in n: x *= a[i][sigma[i]]
    result += x

proc perm[M,N](a: Matrix[M,N]): float =
  let n = toSeq 0..a.high
  for sigma, sign in n.permutations:
    var x = 1.0
    for i in n: x *= a[i][sigma[i]]
    result += x

const
  a = [ [1.0, 2.0]
      , [3.0, 4.0]
      ]
  b = [ [ 1.0,  2,  3,  4]
      , [ 4.0,  5,  6,  7]
      , [ 7.0,  8,  9, 10]
      , [10.0, 11, 12, 13]
      ]
  c = [ [ 0.0,  1,  2,  3,  4]
      , [ 5.0,  6,  7,  8,  9]
      , [10.0, 11, 12, 13, 14]
      , [15.0, 16, 17, 18, 19]
      , [20.0, 21, 22, 23, 24]
      ]

echo "perm: ", a.perm, " det: ", a.det
echo "perm: ", b.perm, " det: ", b.det
echo "perm: ", c.perm, " det: ", c.det


; helper function that returns rest of matrix by col/row
(define (rest matrix i j)
   (define (exclude1 l x) (append (take l (- x 1)) (drop l x)))
   (exclude1
      (map exclude1
         matrix (repeat i (length matrix)))
      j))

; superfunction for determinant and permanent
(define (super matrix math)
   (let loop ((n (length matrix)) (matrix matrix))
      (if (eq? n 1)
         (caar matrix)
         (fold (lambda (x a j)
                  (+ x (* a (lref math (mod j 2)) (super (rest matrix j 1) math))))
            0
            (car matrix)
            (iota n 1)))))

; det/per calculators
(define (det matrix) (super matrix '(-1 1)))
(define (per matrix) (super matrix '( 1 1)))

; ---=( testing )=---------------------
(print (det '(
   (1 2)
   (3 4))))
; ==> -2

(print (per '(
   (1 2)
   (3 4))))
; ==> 10

(print (det '(
   ( 1  2  3  1)
   (-1 -1 -1  2)
   ( 1  3  1  1)
   (-2 -2  0 -1))))
; ==> 26

(print (per '(
   ( 1  2  3  1)
   (-1 -1 -1  2)
   ( 1  3  1  1)
   (-2 -2  0 -1))))
; ==> -10

(print (det '(
   ( 0  1  2  3  4)
   ( 5  6  7  8  9)
   (10 11 12 13 14)
   (15 16 17 18 19)
   (20 21 22 23 24))))
; ==> 0

(print (per '(
   ( 0  1  2  3  4)
   ( 5  6  7  8  9)
   (10 11 12 13 14)
   (15 16 17 18 19)
   (20 21 22 23 24))))
; ==> 6778800


Public Sub Main()

Kill User.home &/ "input.txt"
Rmdir User.home &/ "docs"

'Administrative privileges (sudo) would be required to mess about in Root - I'm not going there!

End


# Apparently GAP can only remove a file, not a directory
RemoveFile("input.txt");
# true
RemoveFile("docs");
# fail


package main
import "os"

func main() {
  os.Remove("input.txt")
  os.Remove("/input.txt")
  os.Remove("docs")
  os.Remove("/docs")
  // recursively removes contents:
  os.RemoveAll("docs")
  os.RemoveAll("/docs")
}


// Gets the first filesystem root.  On most systems this will be / or c:\
def fsRoot = File.listRoots().first()

// Create our list of files (including directories)
def files = [
        new File("input.txt"),
        new File(fsRoot, "input.txt"),
        new File("docs"),
        new File(fsRoot, "docs")
]

/*
We use it.directory to determine whether each file is a regular file or directory.  If it is a directory, we delete
it with deleteDir(), otherwise we just use delete().
 */
files.each{
    it.directory ? it.deleteDir() : it.delete()
}


fcn collapsible(str){			// no Unicode
   sink:=Sink(String);
   str.reduce('wrap(c1,c2){ if(c1!=c2) sink.write(c2); c2 },"");  // prime with \0
   cstr:=sink.close();
   return(str.len()!=cstr.len(), cstr);
}


USING: formatting io kernel math math.combinatorics math.ranges
sequences sets ;
IN: rosetta-code.department-numbers

7 [1,b] 3 <k-permutations>
[ [ first even? ] [ sum 12 = ] bi and ] filter

"{ Police, Sanitation, Fire }" print nl
[ "%[%d, %]\n" printf ] each


!!'Police Sanitation Fire';
!!'------|----------|----';
for p = 2 to 6 by 2 do
    for s = 1 to 7 do
        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;


\ if department numbers are valid, print them on a single line
: fire ( pol san fir -- )
    2dup = if 2drop drop exit then
    2 pick over = if 2drop drop exit then
    rot . swap . . cr ;

\ tries to assign numbers with given policeno and sanitationno
\ and fire = 12 - policeno - sanitationno
: sanitation ( pol san -- )
    2dup = if 2drop exit then             \ no repeated numbers
    12 over - 2 pick -                    \ calculate fireno
    dup 1 < if 2drop drop exit then       \ cannot be less than 1
    dup 7 > if 2drop drop exit then       \ cannot be more than 7
    fire ;

\ tries to assign numbers with given policeno
\ and sanitation = 1, 2, 3, ..., or 7
: police ( pol -- )
    8 1 do dup i sanitation loop drop ;

\ tries to assign numbers with police = 2, 4, or 6
: departments cr                          \ leave input line
    8 2 do i police 2 +loop ;


#!/usr/bin/perl
use strict;
use warnings;
use PDL;
use PDL::NiceSlice;

sub permanent{
	my $mat = shift;
	my $n = shift // $mat->dim(0);
	return undef if $mat->dim(0) != $mat->dim(1);
	return $mat(0,0) if $n == 1;
	my $sum = 0;
	--$n;
	my $m = $mat(1:,1:)->copy;
	for(my $i = 0; $i <= $n; ++$i){
		$sum += $mat($i,0) * permanent($m, $n);
		last if $i == $n;
		$m($i,:) .= $mat($i,1:);
	}
	return sclr($sum);
}

my $M = pdl([[2,9,4], [7,5,3], [6,1,8]]);
print "M = $M\n";
print "det(M) = " . $M->determinant . ".\n";
print "det(M) = " . $M->det . ".\n";
print "perm(M) = " . permanent($M) . ".\n";


import System.IO
import System.Directory

main = do
  removeFile "output.txt"
  removeDirectory "docs"
  removeFile "/output.txt"
  removeDirectory "/docs"


SYSTEM(DIR="docs")   ! create docs in current directory (if not existent), make it current
OPEN (FILE="input.txt", "NEW")    ! in current directory = docs
WRITE(FIle="input.txt", DELETE=1) ! no command to DELETE a DIRECTORY in HicEst

SYSTEM(DIR="C:\docs")             ! create C:\docs (if not existent), make it current
OPEN (FILE="input.txt", "NEW")    ! in current directory = C:\docs
WRITE(FIle="input.txt", DELETE=1)


every dir := !["./","/"] do {
   remove(f := dir || "input.txt")  |stop("failure for file remove ",f)
   rmdir(f := dir || "docs")        |stop("failure for directory remove ",f)
   }


Directory fileNamed("input.txt") remove
Directory directoryNamed("docs") remove
RootDir := Directory clone setPath("/")
RootDir fileNamed("input.txt") remove
RootDir directoryNamed("docs") remove


   load 'files'
   ferase 'input.txt'
   ferase '\input.txt'
   ferase 'docs'
   ferase '\docs'

NB. Or all at once...
   ferase 'input.txt';'/input.txt';'docs';'/docs'


      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.
    3        IF (P.EQ.S) CYCLE SS	!But it must differ from the others.
    4        F = 12 - (P + S)		!The fire department accepts any number, but the sum must be twelve.
    5        IF (F.LE.0 .OR. F.GT.7) CYCLE SS	!Ensure that the only option is within range.
    6        IF ((F - S)*(F - P)) 7,8,7		!And F is to differ from S and from P
    7        WRITE (6,"(3I2)") P,S,F		!If we get here, we have a possible set.
    8      END DO SS		!Next S
    9    END DO PP	!Next P.
      END	!Well, that was straightforward.


' version 15-08-2017
' compile with: fbc -s console

Dim As Integer fire, police, sanitation

Print "police fire sanitation"
Print "----------------------"

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 Using "   #     #       # "; police; fire; sanitation
        End If
    Next
Next

' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End


with javascript_semantics
function minor(sequence a, integer x, integer y)
    integer l = length(a)-1
    sequence result = repeat(repeat(0,l),l)
    for i=1 to l do
        for j=1 to l do
            result[i][j] = a[i+(i>=x)][j+(j>=y)]
        end for
    end for
    return result
end function

function det(sequence a)
    if length(a)=1 then
        return a[1][1]
    end if
    integer res = 0,
            sgn = 1
    for i=1 to length(a) do
        res += sgn*a[1][i]*det(minor(a,1,i))
        sgn *= -1
    end for
    return res
end function

function perm(sequence a)
    if length(a)=1 then
        return a[1][1]
    end if
    integer res = 0
    for i=1 to length(a) do
        res += a[1][i]*perm(minor(a,1,i))
    end for
    return res
end function

constant tests = {
{{1,  2},
 {3,  4}},
--Determinant: -2, permanent: 10
{{2, 9, 4},
 {7, 5, 3},
 {6, 1, 8}},
--Determinant: -360, permanent: 900
{{ 1,  2,  3,  4},
 { 4,  5,  6,  7},
 { 7,  8,  9, 10},
 {10, 11, 12, 13}},
--Determinant: 0, permanent: 29556
{{ 0,  1,  2,  3,  4},
 { 5,  6,  7,  8,  9},
 {10, 11, 12, 13, 14},
 {15, 16, 17, 18, 19},
 {20, 21, 22, 23, 24}},
--Determinant: 0, permanent: 6778800
{{5}},
--Determinant: 5, permanent: 5
{{1,0,0},
 {0,1,0},
 {0,0,1}},
--Determinant: 1, permanent: 1
{{0,0,1},
 {0,1,0},
 {1,0,0}},
--Determinant: -1, Permanent: 1
{{4,3},
 {2,5}},
--Determinant: 14, Permanent: 26
{{2,5},
 {4,3}},
--Determinant: -14, Permanent: 26
{{4,4},
 {2,2}},
--Determinant: 0, Permanent: 16
{{7,    2,      -2,     4},
 {4,    4,      1,      7},
 {11,   -8,     9,      10},
 {10,   5,      12,     13}},
--det:  -4319   permanent:      10723

{{-2,   2,      -3},
 {-1,   1,      3},
 {2 ,   0,      -1}}
--det:  18      permanent:      10
}
for i=1 to length(tests) do
    sequence ti = tests[i]
    ?{det(ti),perm(ti)}
end for


import java.io.File;

public class FileDeleteTest {
    public static boolean deleteFile(String filename) {
        boolean exists = new File(filename).delete();
        return exists;
    }

    public static void test(String type, String filename) {
        System.out.println("The following " + type + " called " + filename +
            (deleteFile(filename) ? " was deleted." : " could not be deleted.")
        );
    }

    public static void main(String args[]) {
        test("file", "input.txt");
        test("file", File.seperator + "input.txt");
        test("directory", "docs");
        test("directory", File.seperator + "docs" + File.seperator);
    }
}


var fso = new ActiveXObject("Scripting.FileSystemObject");

fso.DeleteFile('input.txt');
fso.DeleteFile('c:/input.txt');

fso.DeleteFolder('docs');
fso.DeleteFolder('c:/docs');


# Delete a file
rm("input.txt")

# Delete a directory
rm("docs", recursive = true)


// version 1.0.6

/* testing on Windows 10 which needs administrative privileges
   to delete files from the root */

import java.io.File

fun main(args: Array<String>) {
    val paths = arrayOf("input.txt", "docs", "c:\\input.txt", "c:\\docs")
    var f: File
    for (path in paths) {
        f = File(path)
        if (f.delete())
            println("$path successfully deleted")
        else
            println("$path could not be deleted")
    }
}


Public Sub Main()
Dim siC0, siC1, siC2 As Short
Dim sOut As New String[]
Dim sTemp As String

For siC0 = 2 To 6 Step 2
  For siC1 = 1 To 7
    For siC2 = 1 To 7
      If sic0 + siC1 + siC2 = 12 Then
        If siC0 <> siC1 And siC1 <> siC2 And siC0 <> siC2 Then sOut.Add(Str(siC0) & Str(siC1) & Str(siC2))
      End If
    Next
  Next
Next

Print "\tPolice\tFire\tSanitation"
siC0 = 0

For Each sTemp In sOut
  Inc sic0
  Print "[" & Format(Str(siC0), "00") & "]\t" & Left(sTemp, 1) & "\t" & Mid(sTemp, 2, 1) & "\t" & Right(sTemp, 1)
Next

End


package main

import "fmt"

func main() {
    fmt.Println("Police  Sanitation  Fire")
    fmt.Println("------  ----------  ----")
    count := 0
    for i := 2; i < 7; i += 2 {
        for j := 1; j < 8; j++ {
            if j == i { continue }
            for k := 1; k < 8; k++ {
                if k == i || k == j { continue }
                if i + j + k != 12 { continue }
                fmt.Printf("  %d         %d         %d\n", i, j, k)
                count++
            }
        }
    }
    fmt.Printf("\n%d valid combinations\n", count)
}


// delete file
local(f = file('input.txt'))
#f->delete

// delete directory
// directory must be empty before it can be successfully deleted. A failure is generated if the operation fails.
local(d = dir('docs'))
#d->delete

// delete file in root file system (requires permissions at user OS level)
local(f = file('//input.txt'))
#f->delete

// delete directory in root file system (requires permissions at user OS level)
// directory must be empty before it can be successfully deleted. A failure is generated if the operation fails.
local(d = file('//docs'))
#d->delete


' show where we are
print DefaultDir$

' in here
kill "input.txt"
result=rmdir("Docs")

' from root
kill "\input.txt"
result=rmdir("\Docs")


-- note: fileIO xtra is shipped with Director, i.e. an "internal"
fp = xtra("fileIO").new()
fp.openFile("input.txt", 0)
fp.delete()


erasefile "input.txt
erasefile "/input.txt


os.remove("input.txt")
os.remove("/input.txt")
os.remove("docs")
os.remove("/docs")


class DepartmentNumbers {
    static void main(String[] args) {
        println("Police  Sanitation  Fire")
        println("------  ----------  ----")
        int count = 0
        for (int i = 2; i <= 6; i += 2) {
            for (int j = 1; j <= 7; ++j) {
                if (j == i) continue
                for (int k = 1; k <= 7; ++k) {
                    if (k == i || k == j) continue
                    if (i + j + k != 12) continue
                    println("  $i         $j         $k")
                    count++
                }
            }
        }
        println()
        println("$count valid combinations")
    }
}


10 PRINT "Police Sanitation Fire"
20 PRINT "------|----------|----"
30 FOR P = 2 TO 7 STEP 2
40 FOR S = 1 TO 7
50 IF S = P THEN GOTO 100
60 FOR F = 1 TO 7
70 IF S = F OR F = P THEN GOTO 90
80 IF P+S+F = 12 THEN PRINT USING "   #       #       #";P;F;S
90 NEXT F
100 NEXT S
110 NEXT P


from itertools import permutations
from operator import mul
from math import fsum
from spermutations import spermutations

def prod(lst):
    return reduce(mul, lst, 1)

def perm(a):
    n = len(a)
    r = range(n)
    s = permutations(r)
    return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)

def det(a):
    n = len(a)
    r = range(n)
    s = spermutations(n)
    return fsum(sign * prod(a[i][sigma[i]] for i in r)
                for sigma, sign in s)

if __name__ == '__main__':
    from pprint import pprint as pp

    for a in (
            [
             [1, 2],
             [3, 4]],

            [
             [1, 2, 3, 4],
             [4, 5, 6, 7],
             [7, 8, 9, 10],
             [10, 11, 12, 13]],

            [
             [ 0,  1,  2,  3,  4],
             [ 5,  6,  7,  8,  9],
             [10, 11, 12, 13, 14],
             [15, 16, 17, 18, 19],
             [20, 21, 22, 23, 24]],
        ):
        print('')
        pp(a)
        print('Perm: %s Det: %s' % (perm(a), det(a)))


wd = NotebookDirectory[];
DeleteFile[wd <> "input.txt"]
DeleteFile["/" <> "input.txt"]
DeleteDirectory[wd <> "docs"]
DeleteDirectory["/" <> "docs"]


   delete('input.txt');   % delete local file input.txt
   delete('/input.txt');   % delete file /input.txt
   rmdir('docs');    % remove local directory docs
   rmdir('/docs');   % remove directory /docs


-- Here
deleteFile "input.txt"
-- Root
deleteFile "\input.txt"


:- module delete_file.
:- interface.

:- import_module io.

:- pred main(io::di, io::uo) is det.

:- implementation.

main(!IO) :-
    io.remove_file("input.txt", _, !IO),
    io.remove_file("/input.txt", _, !IO),
    io.remove_file("docs", _, !IO),
    io.remove_file("/docs", _, !IO).


f = new(Nanoquery.IO.File)
f.delete("input.txt")
f.delete("docs")
f.delete("/input.txt")
f.delete("/docs")


using System;
using System.IO;
using System.Console;

module DeleteFile
{
    Main() : void
    {
        when (File.Exists("input.txt")) File.Delete("input.txt");
        try {
            when (File.Exists(@"\input.txt")) File.Delete(@"\input.txt");
        }
        catch {
            |e is UnauthorizedAccessException => WriteLine(e.Message)
        }

        when (Directory.Exists("docs")) Directory.Delete("docs");
        when (Directory.Exists(@"\docs")) Directory.Delete(@"\docs");
    }
}


require 'stats'
permfrom=: ,/@([email protected][ {"_ 1 comb)  NB. get permutations of length x from y possible items

alluniq=: # = #@~.           NB. check items are unique
addto12=: 12 = +/            NB. check items add to 12
iseven=: [email protected](2&|)            NB. check items are even
policeeven=: {[email protected]       NB. check first item is even
conditions=: policeeven *. addto12 *. alluniq

Validnums=: >: i.7           NB. valid Department numbers

getDeptNums=: [: (#~ conditions"1) Validnums {~ permfrom


library(combinat)
perm <- function(A)
{
  stopifnot(is.matrix(A))
  n <- nrow(A)
  if(n != ncol(A)) stop("Matrix is not square.")
  if(n < 1) stop("Matrix has a dimension of size 0.")
  sum(sapply(combinat::permn(n), function(sigma) prod(sapply(1:n, function(i) A[i, sigma[i]]))))
}

#We copy our test cases from the Python example.
testData <- list("Test 1" = rbind(c(1, 2), c(3, 4)),
                 "Test 2" = rbind(c(1, 2, 3, 4), c(4, 5, 6, 7), c(7, 8, 9, 10), c(10, 11, 12, 13)),
                 "Test 3" = rbind(c(0, 1, 2, 3, 4), c(5, 6, 7, 8, 9), c(10, 11, 12, 13, 14),
                               c(15, 16, 17, 18, 19), c(20, 21, 22, 23, 24)))
print(sapply(testData, function(x) list(Determinant = det(x), Permanent = perm(x))))


/* NetRexx */
options replace format comments java crossref symbols binary

runSample(arg)
return

-- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
method isFileDeleted(fn) public static returns boolean
  ff = File(fn)
  fDeleted = ff.delete()
  return fDeleted

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
  parse arg files
  if files = '' then files = 'input.txt F docs D /input.txt F /docs D'
  loop while files.length > 0
    parse files fn ft files
    select case(ft.upper())
      when 'F' then do
        ft = 'File'
        end
      when 'D' then do
        ft = 'Directory'
        end
      otherwise do
        ft = 'File'
        end
      end
    if isFileDeleted(fn) then dl = 'deleted'
    else                      dl = 'not deleted'
    say ft ''''fn'''' dl
    end

  return


(delete-file "input.txt")
(delete-file "/input.txt")
(remove-dir "docs")
(remove-dir "/docs")


import os
removeFile("input.txt")
removeFile("/input.txt")
removeDir("docs")
removeDir("/docs")


use IO;

bundle Default {
  class FileExample {
    function : Main(args : String[]) ~ Nil {
      File->Delete("output.txt");
      File->Delete("/output.txt");

      Directory->Delete("docs");
      Directory->Delete("/docs");
    }
  }
}


public class DepartmentNumbers {
    public static void main(String[] args) {
        System.out.println("Police  Sanitation  Fire");
        System.out.println("------  ----------  ----");
        int count = 0;
        for (int i = 2; i <= 6; i += 2) {
            for (int j = 1; j <= 7; ++j) {
                if (j == i) continue;
                for (int k = 1; k <= 7; ++k) {
                    if (k == i || k == j) continue;
                    if (i + j + k != 12) continue;
                    System.out.printf("  %d         %d         %d\n", i, j, k);
                    count++;
                }
            }
        }
        System.out.printf("\n%d valid combinations", count);
    }
}


(function () {
    'use strict';

    // concatMap :: (a -> [b]) -> [a] -> [b]
    function concatMap(f, xs) {
        return [].concat.apply([], xs.map(f));
    };

    return '(Police, Sanitation, Fire)\n' +
        concatMap(function (x) {
            return concatMap(function (y) {
                return concatMap(function (z) {
                    return z !== y && 1 <= z && z <= 7 ? [
                        [x, y, z]
                    ] : [];
                }, [12 - (x + y)]);
            }, [1, 2, 3, 4, 5, 6, 7]);
        }, [2, 4, 6])
        .map(JSON.stringify)
        .join('\n');
})();


#lang racket
(require math)
(define determinant matrix-determinant)

(define (permanent M)
  (define n (matrix-num-rows M))
  (for/sum ([σ (in-permutations (range n))])
    (for/product ([i n] [σi σ])
      (matrix-ref M i σi))))


sub insert ($x, @xs) { ([flat @xs[0 ..^ $_], $x, @xs[$_ .. *]] for 0 .. @xs) }
sub order ($sg, @xs) { $sg > 0 ?? @xs !! @xs.reverse }

multi σ_permutations ([]) { [] => 1 }

multi σ_permutations ([$x, *@xs]) {
    σ_permutations(@xs).map({ |order($_.value, insert($x, $_.key)) }) Z=> |(1,-1) xx *
}

sub m_arith ( @a, $op ) {
    note "Not a square matrix" and return
      if [||] map { @a.elems cmp @a[$_].elems }, ^@a;
    sum σ_permutations([^@a]).race.map: {
        my $permutation = .key;
        my $term = $op eq 'perm' ?? 1 !! .value;
        for $permutation.kv -> $i, $j { $term *= @a[$i][$j] };
        $term
    }
}

######### helper subs #########
sub hilbert-matrix (\h) {[(1..h).map(-> \n {[(n..^n+h).map: {(1/$_).FatRat}]})]}

sub rat-or-int ($num) {
    return $num unless $num ~~ Rat|FatRat;
    return $num.narrow if $num.narrow.WHAT ~~ Int;
    $num.nude.join: '/';
}

sub say-it ($message, @array) {
    my $max;
    @array.map: {$max max= max $_».&rat-or-int.comb(/\S+/)».chars};
    say "\n$message";
    $_».&rat-or-int.fmt(" %{$max}s").put for @array;
}

########### Testing ###########
my @tests = (
    [
        [ 1, 2 ],
        [ 3, 4 ]
    ],
    [
        [  1,  2,  3,  4 ],
        [  4,  5,  6,  7 ],
        [  7,  8,  9, 10 ],
        [ 10, 11, 12, 13 ]
    ],
    hilbert-matrix 7
);

for @tests -> @matrix {
    say-it 'Matrix:', @matrix;
    say "Determinant:\t", rat-or-int @matrix.&m_arith: <det>;
    say "Permanent:  \t", rat-or-int @matrix.&m_arith: <perm>;
    say '-' x 40;
}


NSFileManager *fm = [NSFileManager defaultManager];

// Pre-OS X 10.5
[fm removeFileAtPath:@"input.txt" handler:nil];
[fm removeFileAtPath:@"/input.txt" handler:nil];
[fm removeFileAtPath:@"docs" handler:nil];
[fm removeFileAtPath:@"/docs" handler:nil];

// OS X 10.5+
[fm removeItemAtPath:@"input.txt" error:NULL];
[fm removeItemAtPath:@"/input.txt" error:NULL];
[fm removeItemAtPath:@"docs" error:NULL];
[fm removeItemAtPath:@"/docs" error:NULL];


Sys.remove "input.txt";;
Sys.remove "/input.txt";;


/*REXX pgm deletes a file */
file= 'afile.txt'                     /*name of a file  to be deleted.*/
res=sysFileDelete(file); Say file 'res='res
File= 'bfile.txt'                     /*name of a file  to be deleted.*/
res=sysFileDelete(file); Say file 'res='res


for Dir in ["/" "./"] do
   try {OS.unlink Dir#"output.txt"}
   catch _ then {System.showInfo "File does not exist."} end
   try {OS.rmDir Dir#"docs"}
   catch _ then {System.showInfo "Directory does not exist."} end
end


using Printf

function findsolution(rng=1:7)
    rst = Matrix{Int}(0, 3)
    for p in rng, f in rng, s in rng
        if p != s != f != p && p + s + f == 12 && iseven(p)
            rst = [rst; p s f]
        end
    end
    return rst
end

function printsolutions(sol::Matrix{Int})
    println("      Pol.   Fire   San.")
    println("      ----   ----   ----")
    for row in 1:size(sol, 1)
        @printf("%2i | %4i%7i%7i\n", row, sol[row, :]...)
    end
end

printsolutions(findsolution())


// version 1.1.2

fun main(args: Array<String>) {
    println("Police  Sanitation  Fire")
    println("------  ----------  ----")
    var count = 0
    for (i in 2..6 step 2) {
        for (j in 1..7) {
            if (j == i) continue
            for (k in 1..7) {
                if (k == i || k == j) continue
                if (i + j + k != 12) continue
                println("  $i         $j         $k")
                count++
            }
        }
    }
    println("\n$count valid combinations")
}


require 'matrix'

class Matrix
  # Add "permanent" method to Matrix class
  def permanent
    r = (0...row_count).to_a # [0,1] (first example), [0,1,2,3] (second example)
    r.permutation.inject(0) do |sum, sigma|
       sum += sigma.zip(r).inject(1){|prod, (row, col)| prod *= self[row, col] }
    end
  end
end

m1 = Matrix[[1,2],[3,4]] # testcases from Python version

m2 = Matrix[[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10], [10, 11, 12, 13]]

m3 = Matrix[[0, 1, 2, 3, 4],
            [5, 6, 7, 8, 9],
            [10, 11, 12, 13, 14],
            [15, 16, 17, 18, 19],
            [20, 21, 22, 23, 24]]

[m1, m2, m3].each do |m|
  puts "determinant:\t #{m.determinant}", "permanent:\t #{m.permanent}"
  puts
end


system("rm -rf docs");
system("rm input.txt");
system("rm -rf /docs");
system("rm /input.txt");


use File::Spec::Functions qw(catfile rootdir);
# here
unlink 'input.txt';
rmdir 'docs';
# root dir
unlink catfile rootdir, 'input.txt';
rmdir catfile rootdir, 'docs';


without js -- (file i/o)
constant root = iff(platform()=LINUX?"/":"C:\\")
?delete_file("input.txt")
?delete_file(root&"input.txt")
?remove_directory("docs")
?remove_directory(root&"docs")


<?php
unlink('input.txt');
unlink('/input.txt');
rmdir('docs');
rmdir('/docs');
?>


print( "Fire", "Police", "Sanitation" )
sol = 0
for f = 1, 7 do
    for p = 1, 7 do
        for s = 1, 7 do
            if s + p + f == 12 and p % 2 == 0 and f ~= p and f ~= s and p ~= s then
                print( f, p, s ); sol = sol + 1
            end
        end
    end
end
print( string.format( "\n%d solutions found", sol ) )


           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


#determines if i, j, k are exclusive numbers
exclusive_numbers := proc(i, j, k)
	if (i = j) or (i = k) or (j = k) then
		return false;
	end if;
	return true;
end proc;

#outputs all possible combinations of numbers that statisfy given conditions
department_numbers := proc()
	local i, j, k;
	printf("Police		Sanitation	Fire\n");
	for i to 7 do
		for j to 7 do
			k := 12 - i - j;
			if (k <= 7) and (k >= 1) and (i mod 2 = 0) and exclusive_numbers(i,j,k) then
				printf("%d		%d		%d\n", i, j, k);
			end if;
		end do;
	end do;
end proc;

department_numbers();


def permutationsSgn[T]: List[T] => List[(Int,List[T])] = {
  case Nil => List((1,Nil))
  case xs => {
    for {
      (x, i) <- xs.zipWithIndex
      (sgn,ys) <- permutationsSgn(xs.take(i) ++ xs.drop(1 + i))
    } yield {
      val sgni = sgn * (2 * (i%2) - 1)
      (sgni, (x :: ys))
    }
  }
}

def det(m:List[List[Int]]) = {
  val summands =
    for {
      (sgn,sigma) <- permutationsSgn((0 to m.length - 1).toList).toList
    }
    yield {
      val factors =
        for (i <- 0 to (m.length - 1))
        yield m(i)(sigma(i))
      factors.toList.foldLeft(sgn)({case (x,y) => x * y})
    }
  summands.toList.foldLeft(0)({case (x,y) => x + y})


import os.

del(Arg), directory(Arg) =>
    rmdir(Arg).

del(Arg), file(Arg) =>
    rm(Arg).

main(Args) =>
    foreach (Arg in Args)
        del(Arg)
    end.


(call 'rm "input.txt")
(call 'rmdir "docs")
(call 'rm "/input.txt")
(call 'rmdir "/docs")


int main(){
   rm("input.txt");
   rm("/input.txt");
   rm("docs");
   rm("/docs");
}


# possible aliases for Remove-Item: rm, del, ri
Remove-Item input.txt
Remove-Item \input.txt  # file system root

Remove-Item -Recurse docs  # recurse for deleting folders including content
Remove-Item -Recurse \docs


DeleteFile("input.txt")
DeleteDirectory("docs","")  ; needs to delete all included files
DeleteFile("/input.txt")
DeleteDirectory("/docs","*.*")  ; deletes all files according to a pattern

DeleteDirectory("/docs","",#PB_FileSystem_Recursive)  ; deletes all files and directories recursive


Select[Permutations[Range[7], {3}], Total[#] == 12 && EvenQ[First[#]] &]


MODULE DepartmentNumbers;
FROM Conversions IMPORT IntToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;

PROCEDURE WriteInt(num : INTEGER);
VAR str : ARRAY[0..16] OF CHAR;
BEGIN
    IntToStr(num,str);
    WriteString(str);
END WriteInt;

VAR i,j,k,count : INTEGER;
BEGIN
    count:=0;

    WriteString("Police  Sanitation  Fire");
    WriteLn;
    WriteString("------  ----------  ----");
    WriteLn;

    FOR i:=2 TO 6 BY 2 DO
        FOR j:=1 TO 7 DO
            IF j=i THEN CONTINUE; END;
            FOR k:=1 TO 7 DO
                IF (k=i) OR (k=j) THEN CONTINUE; END;
                IF i+j+k # 12 THEN CONTINUE; END;
                WriteString("  ");
                WriteInt(i);
                WriteString("         ");
                WriteInt(j);
                WriteString("         ");
                WriteInt(k);
                WriteLn;
                INC(count);
            END;
        END;
    END;

    WriteLn;
    WriteInt(count);
    WriteString(" valid combinations");
    WriteLn;

    ReadChar;
END DepartmentNumbers.


! MATRIX ARITHMETIC ;
BEGIN

    INTEGER PROCEDURE LENGTH(A); ARRAY A;
        LENGTH := UPPERBOUND(A, 1) - LOWERBOUND(A, 1) + 1;

    ! Set MAT to the first minor of A dropping row X and column Y ;
    PROCEDURE MINOR(A, X, Y, MAT); ARRAY A, MAT; INTEGER X, Y;
    BEGIN
        INTEGER I, J, rowA, M; M := LENGTH(A) - 1; ! not a constant;
        FOR I := 1 STEP 1 UNTIL M DO BEGIN
            rowA := IF I < X THEN I ELSE I + 1;
            FOR J := 1 STEP 1 UNTIL M DO
                MAT(I, J) := A(rowA, IF J < Y THEN J else J + 1);
        END
    END MINOR;

    REAL PROCEDURE DET(A); REAL ARRAY A;
    BEGIN
        INTEGER N; N := LENGTH(A);
        IF N = 1 THEN
            DET := A(1, 1)
        ELSE
        BEGIN
            INTEGER I, SIGN;
            REAL SUM;
            SIGN := 1;
            FOR I := 1 STEP 1 UNTIL N DO
            BEGIN
                REAL ARRAY MAT(1:N-1, 1:N-1);
                MINOR(A, 1, I, MAT);
                SUM := SUM + SIGN * A(1, I) * DET(MAT);
                SIGN := SIGN * -1
            END;
            DET := SUM
        END
    END DET;

    REAL PROCEDURE PERM(A); REAL ARRAY A;
    BEGIN
        INTEGER N; N := LENGTH(A);
        IF N = 1 THEN
            PERM := A(1, 1)
        ELSE
        BEGIN
            REAL SUM;
            INTEGER I;

            FOR I := 1 STEP 1 UNTIL N DO
            BEGIN
                REAL ARRAY MAT(1:N-1, 1:N-1);
                MINOR(A, 1, I, MAT);
                SUM := SUM  + A(1, I) * PERM(MAT)
            END;
            PERM := SUM
        END
    END PERM;

    INTEGER SIZE;
    SIZE := ININT;
    BEGIN
        REAL ARRAY A(1:SIZE, 1:SIZE);
        INTEGER I, J;

        FOR I := 1 STEP 1 UNTIL SIZE DO BEGIN
            ! may be need here: INIMAGE;
            FOR J := 1 STEP 1 UNTIL SIZE DO
                A(I, J) := INREAL
        END;
        OUTTEXT("DETERMINANT ... : "); OUTREAL(DET (A), 10, 20); OUTIMAGE;
        OUTTEXT("PERMANENT ..... : "); OUTREAL(PERM(A), 10, 20); OUTIMAGE;
    END

    COMMENT  THE FIRST INPUT IS THE SIZE OF THE MATRIX, FOR EXAMPLE:

    ! 2
    ! 1 2
    ! 3 4
    ! DETERMINANT: -2.0
    ! PERMANENT: 10.0 ;

    COMMENT
    ! 5
    ! 0 1 2 3 4
    ! 5 6 7 8 9
    ! 10 11 12 13 14
    ! 15 16 17 18 19
    ! 20 21 22 23 24
    ! DETERMINANT: 0.0
    ! PERMANENT: 6778800.0 ;

END


import os
# current directory
os.remove("output.txt")
os.rmdir("docs")
# root directory
os.remove("/output.txt")
os.rmdir("/docs")


file.remove("input.txt")
file.remove("/input.txt")

# or
file.remove("input.txt", "/input.txt")

# or
unlink("input.txt"); unlink("/input.txt")

# directories needs the recursive flag
unlink("docs", recursive = TRUE)
unlink("/docs", recursive = TRUE)


#lang racket

;; here
(delete-file "input.txt")
(delete-directory "docs")
(delete-directory/files "docs") ; recursive deletion

;; in the root
(delete-file "/input.txt")
(delete-directory "/docs")
(delete-directory/files "/docs")

;; or in the root with relative paths
(parameterize ([current-directory "/"])
  (delete-file "input.txt")
  (delete-directory "docs")
  (delete-directory/files "docs"))


unlink 'input.txt';
unlink '/input.txt';
rmdir 'docs';
rmdir '/docs';


'input.txt'  delete
'/input.txt' delete
'docs'  rmdir
'/docs' rmdir


; Local.
delete %input.txt
delete-dir %docs/

; Root.
delete %/input.txt
delete-dir %/docs/


'input.txt file:delete
'/input.txt file:delete


:- module department_numbers.
:- interface.

:- import_module io.
:- pred main(io::di, io::uo) is cc_multi.

:- implementation.

:- import_module int, list, solutions, string.

main(!IO) :-
    io.print_line("P S F", !IO),
    unsorted_aggregate(department_number, print_solution, !IO).

:- pred print_solution({int, int, int}::in, io::di, io::uo) is det.

print_solution({P, S, F}, !IO) :-
    io.format("%d %d %d\n", [i(P), i(S), i(F)], !IO).

:- pred department_number({int, int, int}::out) is nondet.

department_number({Police, Sanitation, Fire}) :-
    list.member(Police, [2, 4, 6]),
    list.member(Sanitation, 1 .. 7),
    list.member(Fire, 1 .. 7),
    Police \= Sanitation,
    Police \= Fire,
    Sanitation \= Fire,
    Police + Sanitation + Fire = 12.


type Solution = tuple[p, s, f: int]

iterator solutions(max, total: Positive): Solution =
  for p in countup(2, max, 2):
    for s in 1..max:
      if s == p: continue
      let f = total - p - s
      if f notin [p, s] and f in 1..max:
        yield (p, s, f)

echo "P S F"
for sol in solutions(7, 12):
  echo sol.p, " ", sol.s, " ", sol.f


class Program {
  function : Main(args : String[]) ~ Nil {
    sol := 1;
    "\t\tFIRE\tPOLICE\tSANITATION"->PrintLine();
    for( f := 1; f < 8; f+=1; ) {
      for( p := 1; p < 8; p+=1; ) {
        for( s:= 1; s < 8; s+=1; ) {
          if( f <> p & f <> s & p <> s & ( p and 1 ) = 0 & ( f + s + p = 12 ) ) {
            "SOLUTION #{$sol}: \t{$f}\t{$p}\t{$s}"->PrintLine();
            sol += 1;
          };
        };
      };
    };
  }
}


real vector range1(real scalar n, real scalar i) {
	if (i < 1 | i > n) {
		return(1::n)
	} else if (i == 1) {
		return(2::n)
	} else if (i == n) {
		return(1::n-1)
	} else {
		return(1::i-1\i+1::n)
	}
}

real matrix submat(real matrix a, real scalar i, real scalar j) {
	return(a[range1(rows(a), i), range1(cols(a), j)])
}

real scalar sumrec(real matrix a, real scalar x) {
	real scalar n, s, p
	n = rows(a)
	if (n==1) return(a[1,1])
	s = 0
	p = 1
	for (i=1; i<=n; i++) {
		s = s+p*a[i,1]*sumrec(submat(a, i, 1), x)
		p = p*x
	}
	return(s)
}


package require math::linearalgebra
package require struct::list

proc permanent {matrix} {
    for {set plist {};set i 0} {$i<[llength $matrix]} {incr i} {
	lappend plist $i
    }
    foreach p [::struct::list permutations $plist] {
	foreach i $plist j $p {
	    lappend prod [lindex $matrix $i $j]
	}
	lappend sum [::tcl::mathop::* {*}$prod[set prod {}]]
    }
    return [::tcl::mathop::+ {*}$sum]
}


/*REXX program deletes a file and a folder in the  current directory  and  the root.    */
trace off                                        /*suppress REXX error messages from DOS*/
aFile= 'input.txt'                               /*name of a  file  to be deleted.      */
aDir = 'docs'                                    /*name of a folder to be removed.      */
               do j=1  for 2                     /*perform this  DO  loop exactly twice.*/
               'ERASE'  aFile                    /*erase this  file in the current dir. */
               'RMDIR'  "/s /q"  aDir            /*remove the folder "  "     "     "   */
               if j==1  then 'CD \'              /*make the  current dir  the  root dir.*/
               end                               /* [↑]  just do   CD \    command once.*/
                                                 /*stick a fork in it,  we're all done. */


File.delete("output.txt", "/output.txt")
Dir.delete("docs")
Dir.delete("/docs")


'------ delete input.txt ----------------
kill "input.txt"   ' this is where we are
kill "/input.txt"  ' this is the root

' ---- delete directory docs ----------
result = rmdir("Docs")  ' directory where we are
result = rmdir("/Docs") ' root directory


use std::io::{self, Write};
use std::fs::{remove_file,remove_dir};
use std::path::Path;
use std::{process,display};

const FILE_NAME: &'static str = "output.txt";
const DIR_NAME : &'static str = "docs";

fn main() {
    delete(".").and(delete("/"))
               .unwrap_or_else(|e| error_handler(e,1));
}

fn delete<P>(root: P) -> io::Result<()>
    where P: AsRef<Path>
{
    remove_file(root.as_ref().join(FILE_NAME))
        .and(remove_dir(root.as_ref().join(DIR_NAME)))
}

fn error_handler<E: fmt::Display>(error: E, code: i32) -> ! {
    let _ = writeln!(&mut io::stderr(), "{:?}", error);
    process::exit(code)
}


import java.util._
import java.io.File

object FileDeleteTest extends App {
  def deleteFile(filename: String) = { new File(filename).delete() }

  def test(typ: String, filename: String) = {
    System.out.println("The following " + typ + " called " + filename +
      (if (deleteFile(filename)) " was deleted." else " could not be deleted."))
  }
  test("file", "input.txt")
  test("file", File.separatorChar + "input.txt")
  test("directory", "docs")
  test("directory", File.separatorChar + "docs" + File.separatorChar)
}


(*
 * 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
 *          "this is what my first lines of ocaml might look like"
 *
 *          The only reason im publishing this is that nobody has yet submitted an example in ocaml
 *)

(* sfp is just a convenience to put a combination if sanitation (s) fire (f) and police (p) department in one record*)
type sfp = {s : int; f : int; p : int}

(* Convenience Function to print a single sfp Record *)
let print_sfp e =
    Printf.printf "%d %d %d\n" e.s e.f e.p

(* Convenience Function to print a list of sfp Records*)
let print_sfp_list l =
    l |> List.iter print_sfp

(* Computes sum of list l *)
let sum l = List.fold_left (+) 0 l

(* checks if element e is in list l *)
let element_in_list e l =
    l |> List.find_map (fun x -> if x == e then Some(e) else None) <> None

(* returns a list with only the unique elements of list l *)
let uniq l =
    let rec uniq_helper acc l =
        match l with
        | [] -> acc
        | h::t -> if element_in_list h t then uniq_helper acc t else uniq_helper (h::acc) t in
    uniq_helper [] l |> List.rev

(* checks wheter or not list l only contains unique elements *)
let is_uniq l = uniq l = l

(* computes all combinations for a given list of sanitation, fire & police departments
   im not very proud of this function...maybe someone with some experience can clean it up? ;)
*)
let department_numbers sl fl pl =
    sl |> List.fold_left (fun aa s ->
        fl |> List.fold_left (fun fa f ->
            pl |> List.fold_left (fun pa p ->
                if
                    sum [s;f;p] == 12 &&
                    is_uniq [s;f;p] then
                        {s = s; f = f; p = p} :: pa
                else
                    pa) []
        |> List.append fa) []
    |> List.append aa) []

(* "main" function *)
let _ =
    let s = [1;2;3;4;5;6;7] in
    let f = [1;2;3;4;5;6;7] in
    let p = [2;4;6] in
    let result = department_numbers s f p in
    print_endline "S F P";
    print_sfp_list result;


Module Module1

    Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,)
        Dim length = a.GetLength(0) - 1
        Dim result(length - 1, length - 1) As Double
        For i = 1 To length
            For j = 1 To length
                If i < x AndAlso j < y Then
                    result(i - 1, j - 1) = a(i - 1, j - 1)
                ElseIf i >= x AndAlso j < y Then
                    result(i - 1, j - 1) = a(i, j - 1)
                ElseIf i < x AndAlso j >= y Then
                    result(i - 1, j - 1) = a(i - 1, j)
                Else
                    result(i - 1, j - 1) = a(i, j)
                End If
            Next
        Next
        Return result
    End Function

    Function Det(a As Double(,)) As Double
        If a.GetLength(0) = 1 Then
            Return a(0, 0)
        Else
            Dim sign = 1
            Dim sum = 0.0
            For i = 1 To a.GetLength(0)
                sum += sign * a(0, i - 1) * Det(Minor(a, 0, i))
                sign *= -1
            Next
            Return sum
        End If
    End Function

    Function Perm(a As Double(,)) As Double
        If a.GetLength(0) = 1 Then
            Return a(0, 0)
        Else
            Dim sum = 0.0
            For i = 1 To a.GetLength(0)
                sum += a(0, i - 1) * Perm(Minor(a, 0, i))
            Next
            Return sum
        End If
    End Function

    Sub WriteLine(a As Double(,))
        For i = 1 To a.GetLength(0)
            Console.Write("[")
            For j = 1 To a.GetLength(1)
                If j > 1 Then
                    Console.Write(", ")
                End If
                Console.Write(a(i - 1, j - 1))
            Next
            Console.WriteLine("]")
        Next
    End Sub

    Sub Test(a As Double(,))
        If a.GetLength(0) <> a.GetLength(1) Then
            Throw New ArgumentException("The dimensions must be equal")
        End If

        WriteLine(a)
        Console.WriteLine("Permanant  : {0}", Perm(a))
        Console.WriteLine("Determinant: {0}", Det(a))
        Console.WriteLine()
    End Sub

    Sub Main()
        Test({{1, 2}, {3, 4}})
        Test({{1, 2, 3, 4}, {4, 5, 6, 7}, {7, 8, 9, 10}, {10, 11, 12, 13}})
        Test({{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}, {10, 11, 12, 13, 14}, {15, 16, 17, 18, 19}, {20, 21, 22, 23, 24}})
    End Sub

End Module


$ include "seed7_05.s7i";
  include "osfiles.s7i";

const proc: main is func
  begin
    removeFile("input.txt");
    removeFile("/input.txt");
    removeTree("docs");
    removeTree("/docs");
  end func;


// Delete locally (relative to "the folder")
delete file "input.txt"
delete folder "docs"

// Delete at the file system root
delete file "/input.txt"
delete folder "/docs"


# here
%f'input.txt' -> delete;
%d'docs'      -> delete;

# root dir
Dir.root + %f'input.txt' -> delete;
Dir.root + %d'docs'      -> delete;


(File newNamed: 'input.txt') delete.
(File newNamed: '/input.txt') delete.
(Directory newNamed: 'docs') delete.
(Directory newNamed: '/docs') delete.


File remove: 'input.txt'.
File remove: 'docs'.
File remove: '/input.txt'.
File remove: '/docs'


OS.FileSys.remove "input.txt";
OS.FileSys.remove "/input.txt";
OS.FileSys.rmDir "docs";
OS.FileSys.rmDir "/docs";


#!/usr/bin/perl

my @even_numbers;

for (1..7)
{
  if ( $_ % 2 == 0)
  {
    push @even_numbers, $_;
  }
}

print "Police\tFire\tSanitation\n";

foreach my $police_number (@even_numbers)
{
  for my $fire_number (1..7)
  {
    for my $sanitation_number (1..7)
    {
      if ( $police_number + $fire_number + $sanitation_number == 12 &&
           $police_number != $fire_number &&
           $fire_number != $sanitation_number &&
           $sanitation_number != $police_number)
      {
        print "$police_number\t$fire_number\t$sanitation_number\n";
      }
    }
  }
}


Option Base 1
Private Function minor(a As Variant, x As Integer, y As Integer) As Variant
    Dim l As Integer: l = UBound(a) - 1
    Dim result() As Double
    If l > 0 Then ReDim result(l, l)
    For i = 1 To l
        For j = 1 To l
            result(i, j) = a(i - (i >= x), j - (j >= y))
        Next j
    Next i
    minor = result
End Function

Private Function det(a As Variant)
    If IsArray(a) Then
        If UBound(a) = 1 Then
            On Error GoTo err
            det = a(1, 1)
            Exit Function
        End If
    Else
        det = a
        Exit Function
    End If
    Dim sgn_ As Integer: sgn_ = 1
    Dim res As Integer: res = 0
    Dim i As Integer
    For i = 1 To UBound(a)
        res = res + sgn_ * a(1, i) * det(minor(a, 1, i))
        sgn_ = sgn_ * -1
    Next i
    det = res
    Exit Function
err:
    det = a(1)
End Function

Private Function perm(a As Variant) As Double
    If IsArray(a) Then
        If UBound(a) = 1 Then
            On Error GoTo err
            perm = a(1, 1)
            Exit Function
        End If
    Else
        perm = a
        Exit Function
    End If
    Dim res As Double
    Dim i As Integer
    For i = 1 To UBound(a)
        res = res + a(1, i) * perm(minor(a, 1, i))
    Next i
    perm = res
    Exit Function
err:
    perm = a(1)
End Function

Public Sub main()
    Dim tests(13) As Variant
    tests(1) = [{1,  2; 3,  4}]
    '--Determinant: -2, permanent: 10
    tests(2) = [{2, 9, 4; 7, 5, 3; 6, 1, 8}]
    '--Determinant: -360, permanent: 900
    tests(3) = [{ 1,  2,  3,  4; 4,  5,  6,  7; 7,  8,  9, 10; 10, 11, 12, 13}]
    '--Determinant: 0, permanent: 29556
    tests(4) = [{ 0,  1,  2,  3,  4; 5,  6,  7,  8,  9; 10, 11, 12, 13, 14; 15, 16, 17, 18, 19; 20, 21, 22, 23, 24}]
    '--Determinant: 0, permanent: 6778800
    tests(5) = [{5}]
    '--Determinant: 5, permanent: 5
    tests(6) = [{1,0,0; 0,1,0; 0,0,1}]
    '--Determinant: 1, permanent: 1
    tests(7) = [{0,0,1; 0,1,0; 1,0,0}]
    '--Determinant: -1, Permanent: 1
    tests(8) = [{4,3; 2,5}]
    '--Determinant: 14, Permanent: 26
    tests(9) = [{2,5; 4,3}]
    '--Determinant: -14, Permanent: 26
    tests(10) = [{4,4; 2,2}]
    '--Determinant: 0, Permanent: 16
    tests(11) = [{7,    2,      -2,     4; 4,    4,      1,      7; 11,   -8,     9,      10; 10,   5,      12,     13}]
    '--det:  -4319   permanent:      10723
    tests(12) = [{-2,   2,      -3; -1,   1,      3; 2 ,   0,      -1}]
    '--det:  18      permanent:      10
    tests(13) = 13
    Debug.Print "Determinant", "Builtin det", "Permanent"
    For i = 1 To 12
        Debug.Print det(tests(i)), WorksheetFunction.MDeterm(tests(i)), perm(tests(i))
    Next i
    Debug.Print det(tests(13)), "error", perm(tests(13))
End Sub


file delete input.txt /input.txt

# preserve directory if non-empty
file delete docs /docs

# delete even if non-empty
file delete -force docs /docs


needs shell
" docs" remove
" input.txt" remove


$$ MODE TUSCRIPT
- delete file
SET status = DELETE ("input.txt")
- delete directory
SET status = DELETE ("docs",-std-)


rm -rf docs
rm input.txt
rm -rf /docs
rm /input.txt


decl file f
f.delete "input.txt"
f.delete "docs"
f.delete "/input.txt"
f.delete "/docs"


Option Explicit

Sub DeleteFileOrDirectory()
Dim myPath As String
    myPath = "C:\Users\surname.name\Desktop\Docs"
'delete file
    Kill myPath & "\input.txt"
'delete Directory
    RmDir myPath
End Sub


printf(1,"Police  Sanitation  Fire\n")
printf(1,"------  ----------  ----\n")
integer solutions = 0
for police=2 to 7 by 2 do
    for sanitation=1 to 7 do
        if sanitation!=police then
            integer fire = 12-(police+sanitation)
            if fire>=1
            and fire<=7
            and fire!=police
            and fire!=sanitation then
                printf(1,"  %d         %d         %d\n", {police,sanitation,fire})
                solutions += 1
            end if
        end if
    end for
end for
printf(1,"\n%d solutions found\n", solutions)


<?php

$valid = 0;
for ($police = 2 ; $police <= 6 ; $police += 2) {
    for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {
        $fire = 12 - $police - $sanitation;
        if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {
            echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;
            $valid++;
        }
    }
}
echo $valid, ' valid combinations found.', PHP_EOL;


Set oFSO = CreateObject( "Scripting.FileSystemObject" )

oFSO.DeleteFile "input.txt"
oFSO.DeleteFolder "docs"

oFSO.DeleteFile "\input.txt"
oFSO.DeleteFolder "\docs"

'Using Delete on file and folder objects

dim fil, fld

set fil = oFSO.GetFile( "input.txt" )
fil.Delete
set fld = oFSO.GetFolder( "docs" )
fld.Delete

set fil = oFSO.GetFile( "\input.txt" )
fil.Delete
set fld = oFSO.GetFolder( "\docs" )
fld.Delete


// In current directory
File_Delete("input.txt", OK)
File_Rmdir("docs")

// In the root directory
File_Delete("/input.txt", OK)
File_Rmdir("/docs")


'Current Directory
IO.Directory.Delete("docs")
IO.Directory.Delete("docs", True) 'also delete files and sub-directories
IO.File.Delete("output.txt")

'Root
IO.Directory.Delete("\docs")
IO.File.Delete("\output.txt")

'Root, platform independent
IO.Directory.Delete(IO.Path.DirectorySeparatorChar & "docs")
IO.File.Delete(IO.Path.DirectorySeparatorChar & "output.txt")


import "io" for File

File.delete("input.txt")

// check it worked
System.print(File.exists("input.txt"))


;syscall numbers for readability. :]
%define sys_rmdir 40
%define sys_unlink 10

section .text
	global _start

	_start:
		mov ebx, fn
		mov eax, sys_unlink
		int 0x80
		test eax, eax
		js _ragequit

		mov ebx, dn
		mov eax, sys_rmdir
		int 0x80

		mov ebx, rfn
		mov eax, sys_unlink
		int 0x80
		cmp eax, 0
		je _exit

		_ragequit:
			mov edx, err_len
			mov ecx, err_msg
			mov ebx, 4
			mov eax ,1
			int 0x80

		_exit:
			push 0x1
			mov eax, 1
			push eax
			int 0x80
			ret

section .data
fn		db 'input.txt',0
rfn		db '/input.txt',0
dn		db 'doc',0

err_msg		db "Something went wrong! :[",0xa
err_len		equ $-err_msg


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]).


(de numbers NIL
   (co 'numbers
      (let N 7
         (for P N
            (for S N
               (for F N
                  (yield (list P S F)) ) ) ) ) ) )
(de departments NIL
   (use (L)
      (while (setq L (numbers))
         (or
            (bit? 1 (car L))
            (= (car L) (cadr L))
            (= (car L) (caddr L))
            (= (cadr L) (caddr L))
            (<> 12 (apply + L))
            (println L) ) ) ) )
(departments)


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.

main :-
    write("P F S"), nl,
    forall(assign(Police, Fire, Sanitation), format("~w ~w ~w~n", [Police, Fire, Sanitation])),
    halt.

?- main.


var [const] GSL=Import("zklGSL");	// libGSL (GNU Scientific Library)
fcn perm(A){  // should verify A is square
   numRows:=A.rows;
   Utils.Helpers.permute(numRows.toList()).reduce(  // permute(0,1,..numRows)
      'wrap(s,pm){ s + numRows.reduce('wrap(x,i){ x*A[i,pm[i]] },1.0) },
      0.0)
}
test:=fcn(A){
   println(A.format());
   println("Permanent: %.2f, determinant: %.2f".fmt(perm(A),A.det()));
};


remove, "input.txt";
remove, "/input.txt";
rmdir, "docs";
rmdir, "/docs";


const std = @import("std");
const fs = std.fs;

pub fn main() !void {
    const here = fs.cwd();
    try here.deleteFile("input.txt");
    try here.deleteDir("docs");

    const root = try fs.openDirAbsolute("/", .{});
    try root.deleteFile("input.txt");
    try root.deleteDir("docs");
}


zkl: System.cmd((System.isWindows and "del" or "unlink") + " input.txt")
0
zkl: System.cmd((System.isWindows and "del" or "unlink") + " /input.txt")
unlink: cannot unlink ‘/input.txt’: No such file or directory
256
zkl: System.cmd("rmdir docs")
rmdir: failed to remove ‘docs’: Directory not empty
256
zkl: System.cmd("rm -r docs")
0
zkl: System.cmd("rm -r /docs")
rm: cannot remove ‘/docs’: No such file or directory
256


from itertools import permutations

def solve():
    c, p, f, s = "\\,Police,Fire,Sanitation".split(',')
    print(f"{c:>3}  {p:^6} {f:^4} {s:^10}")
    c = 1
    for p, f, s in permutations(range(1, 8), r=3):
        if p + s + f == 12 and p % 2 == 0:
            print(f"{c:>3}: {p:^6} {f:^4} {s:^10}")
            c += 1

if __name__ == '__main__':
    solve()


  [ 2dup = iff
      [ 2drop drop ] done
    dip over swap over = iff
      [ 2drop drop ] done
    rot echo sp
    swap echo sp
    echo cr ]                is fire      ( pol san fir --> )

  [ 2dup = iff 2drop done
    12 over -
    dip over swap -
    dup 1 < iff
      [ 2drop drop ] done
    dup 7 > iff
      [ 2drop drop ] done
    fire ]                  is sanitation  (   pol san --> )

   [ 7 times
       [ dup
         i^ 1+ sanitation ]
     drop ]                 is police      (       pol --> )

   [ cr ' [ 2 4 6 ]
     witheach police ]      is departments (           --> )

  departments


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)


#lang racket
(cons '(police fire sanitation)
      (filter (λ (pfs) (and (not (check-duplicates pfs))
                            (= 12 (apply + pfs))
                            pfs))
              (cartesian-product (range 2 8 2) (range 1 8) (range 1 8))))


for (1..7).combinations(3).grep(*.sum == 12) {
    for   .permutations\  .grep(*.[0] %%  2) {
        say <police fire sanitation> Z=> .list;
    }
}


/*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 "   "    "   */
#=0                                              /*number of solutions found  (so far). */
    do     p=1  for 7;     if p//2  then iterate /*try numbers for the police department*/
      do   s=1  for 7;     if s==p  then iterate /* "     "     "   "  fire        "    */
        do f=1  for 7;     if f==s  then iterate /* "     "     "   "  sanitation  "    */
        if p + s + f \== 12         then iterate /*check if sum of department nums ¬= 12*/
        #= # + 1                                 /*bump count of the number of solutions*/
        say center(p,6) center(s,10) center(f,4) /*display one possible solution.       */
        end   /*s*/
      end     /*f*/
    end       /*p*/

say '══════ ══════════ ════'                     /*   "     head separator "   "    "   */
say                                              /*stick a fork in it,  we're all done. */
say #  ' solutions found.'                       /*also, show the # of solutions found. */


sanitation= 0
see "police fire sanitation" + nl

for police = 2 to 7 step 2
    for fire = 1 to 7
        if fire = police
           loop
        ok
        sanitation = 12 - police - fire
        if sanitation = fire or sanitation = police
           loop
        ok
        if sanitation >= 1 and sanitation <= 7
           see "   " + police + "      " + fire + "       " + sanitation + nl
        ok
    next
next


(1..7).to_a.permutation(3){|p| puts p.join if p.first.even? && p.sum == 12 }


extern crate num_iter;
fn main() {
    println!("Police Sanitation Fire");
    println!("----------------------");

    for police in num_iter::range_step(2, 7, 2) {
        for sanitation in 1..8 {
            for fire in 1..8 {
                if police != sanitation
                    && sanitation != fire
                    && fire != police
                    && police + fire + sanitation == 12
                {
                    println!("{:6}{:11}{:4}", police, sanitation, fire);
                }
            }
        }
    }
}


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
  .filter{ n => n._1 + n._2 + n._3 == 12 }                            // Keep only numbers that add to 12
}

{
println( "(Police, Sanitation, Fire)")
println( depts.mkString("\n") )
}


RadiusDistribution = NormalDistribution[0, 1];
AngleDistribution = UniformDistribution[{0, Pi}];

(*Mathematica has built in transformation functions, but this seems clearer given the way the instructions were written.*)
ToCartesian[{r_, a_}] := ToCartesian[{[email protected], a - Pi}] /; Negative[r];
ToCartesian[{r_, a_}] := FromPolarCoordinates[{r, a}];

newData =
  ToCartesian /@
   Transpose[{RandomVariate[RadiusDistribution, 100],
     RandomVariate[AngleDistribution, 100]}];

TableForm[Results[#, newData] & /@ Range[4], TableSpacing -> 5]


@(1..7)->combinations(3, {|*a|
    a.sum == 12 || next
    a.permutations {|*b|
        b[0].is_even || next
        say (%w(police fire sanitation) ~Z b -> join(" "))
    }
})


let res = [2, 4, 6].map({x in
  return (1...7)
      .filter({ $0 != x })
      .map({y -> (Int, Int, Int)? in
        let z = 12 - (x + y)

        guard y != z && 1 <= z && z <= 7 else {
          return nil
        }

        return (x, y, z)
      }).compactMap({ $0 })
}).flatMap({ $0 })

for result in res {
  print(result)
}


# Procedure named ".." returns list of integers from 1 to max.
proc .. max {
  for {set i 1} {$i <= $max} {incr i} {
    lappend l $i
  }
  return $l
}

# Procedure named "anyEqual" returns true if any elements are equal,
# false otherwise.
proc anyEqual l {
  if {[llength [lsort -unique $l]] != [llength $l]} {
    return 1
  }
  return 0
}

# Procedure named "odd" tells whether a value is odd or not.
proc odd n {
  expr $n %2 != 0
}

# Procedure named "sum" sums its parameters.
proc sum args {
  expr [join $args +]
}

# Create lists of candidate numbers using proc ".."
set sanitation [.. 7]
set fire $sanitation
# Filter even numbers for police stations (remove odd ones).
set police [lmap e $sanitation {
  if [odd $e] continue
  set e
}]

# Try all combinations and display acceptable ones.
set valid 0
foreach p $police {
  foreach s $sanitation {
    foreach f $fire {
      # Check for equal elements in list.
      if [anyEqual [list $p $s $f]] continue
      # Check for sum of list elements.
      if {[sum $p $s $f] != 12} continue
      puts "$p $s $f"
      incr valid
    }
  }
}
puts "$valid valid combinations found."


   PRINT "Police Sanitation Fire"
   PRINT "------|----------|----"
10 LET P = P + 2
   LET S = 0
20 LET S = S + 1
   LET F = 0
   IF S = P THEN GOTO 20
30 LET F = F + 1
   IF S = F THEN GOTO 30
   IF F = P THEN GOTO 30
   IF P + S + F = 12 THEN PRINT "  ",P,"        ", S,"       ", F
   IF F < 7 THEN GOTO 30
   IF S < 7 THEN GOTO 20
   IF P < 6 THEN GOTO 10


#lang transd

MainModule : {
    _start: (lambda
        (lout "Police | Sanit. | Fire")
        (for i in Range(1 8) where (not (mod i 2)) do
            (for j in Range(1 8) where (neq i j) do
                (for k in Range(1 8) where (and (neq i k) (neq j k)) do
           (if (eq (+ i j k) 12) (lout i "        " j "        " k)))))
    )
}


// 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}`);
    }
  }
}


Module Module1

    Sub Main()
        For p = 2 To 7 Step 2
            For s = 1 To 7
                Dim f = 12 - p - s
                If s >= f Then
                    Exit For
                End If
                If f > 7 Then
                    Continue For
                End If
                If s = p OrElse f = p Then
                    Continue For 'not even necessary
                End If
                Console.WriteLine($"Police:{p}, Sanitation:{s}, Fire:{f}")
                Console.WriteLine($"Police:{p}, Sanitation:{f}, Fire:{s}")
            Next
        Next
    End Sub

End Module


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")
}


with Ada.Text_IO;  use Ada.Text_IO;

procedure Delegation is
   package Things is
      -- We need a common root for our stuff
      type Object is tagged null record;
      type Object_Ptr is access all Object'Class;

      -- Objects that have operation thing
      type Substantial is new Object with null record;
      function Thing (X : Substantial) return String;

      -- Delegator objects
      type Delegator is new Object with record
         Delegate : Object_Ptr;
      end record;
      function Operation (X : Delegator) return String;

      No_Thing  : aliased Object;      -- Does not have thing
      Has_Thing : aliased Substantial; -- Has one
   end Things;

   package body Things is
      function Thing (X : Substantial) return String is
      begin
         return "delegate implementation";
      end Thing;

      function Operation (X : Delegator) return String is
      begin
         if X.Delegate /= null and then X.Delegate.all in Substantial'Class then
            return Thing (Substantial'Class (X.Delegate.all));
         else
            return "default implementation";
         end if;
      end Operation;
   end Things;

   use Things;

   A : Delegator; -- Without a delegate
begin
   Put_Line (A.Operation);
   A.Delegate := No_Thing'Access; -- Set no thing
   Put_Line (A.Operation);
   A.Delegate := Has_Thing'Access; -- Set a thing
   Put_Line (A.Operation);
end Delegation;


System.print("Police  Sanitation  Fire")
System.print("------  ----------  ----")
var count = 0
for (h in 1..3) {
    var i = h * 2
    for (j in 1..7) {
        if (j != i) {
            for (k in 1..7) {
                if ((k != i && k != j) && (i + j + k == 12) ) {
                    System.print("  %(i)         %(j)         %(k)")
                    count = count + 1
                }
            }
        }
    }
}
System.print("\n%(count) valid combinations")


\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


class Delegator {
    public generic delegate = none

    public function operation {
        if (typeof(delegate) == "none") {
            return "default implementation"
        }
        return delegate()
    }
}

function thing {
    return "delegate implementation"
}

// default, no delegate
var d = new Delegator()
println (d.operation())

// delegate
var d1 = new Delegator()
d1.delegate = thing
println (d1.operation())


text
thing(void)
{
    return "delegate implementation";
}

text
operation(record delegator)
{
    text s;

    if (r_key(delegator, "delegate")) {
        if (r_key(delegator["delegate"], "thing")) {
            s = call(r_query(delegator["delegate"], "thing"));
        } else {
            s = "default implementation";
        }
    } else {
        s = "default implementation";
    }

    return s;
}

integer
main(void)
{
    record delegate, delegator;

    o_text(operation(delegator));
    o_byte('\n');

    r_link(delegator, "delegate", delegate);
    o_text(operation(delegator));
    o_byte('\n');

    r_put(delegate, "thing", thing);
    o_text(operation(delegator));
    o_byte('\n');

    return 0;
}


# An Algol 68 approximation of delegates                                #

# The delegate mode - the delegate is a STRUCT with a single field      #
# that is a REF PROC STRING. If this is NIL, it doesn't implement       #
# thing                                                                 #
MODE DELEGATE  = STRUCT( REF PROC STRING thing );

# A delegator mode that will invoke the delegate's thing method         #
# - if there is a delegate and the delegate has a thing method          #
MODE DELEGATOR = STRUCT( REF DELEGATE delegate
                       , PROC( REF DELEGATE )STRING thing
                       );

# constructs a new DELEGATE with the specified PROC as its thing        #
# Algol 68 HEAP is like "new" in e.g. Java, but it can't take           #
# parameters, so this PROC does the equivalent                          #
PROC new delegate = ( REF PROC STRING thing )REF DELEGATE:
    BEGIN
        REF DELEGATE result = HEAP DELEGATE;
        thing OF result := thing;

        result
    END # new delegate #
;

# constructs a new DELEGATOR with the specified DELEGATE                #
PROC new delegator = ( REF DELEGATE delegate )REF DELEGATOR:
    HEAP DELEGATOR := ( delegate
                      , # anonymous PROC to invoke the delegate's thing #
                        ( REF DELEGATE delegate )STRING:
                            IF delegate IS REF DELEGATE(NIL)
                            THEN
                                # we have no delegate #
                                "default implementation"

                            ELIF thing OF delegate IS REF PROC STRING(NIL)
                            THEN
                                # the delegate doesn't have an implementation #
                                "default implementation"

                            ELSE
                                # the delegate can thing #
                                thing OF delegate

                            FI
                      )
;

# invokes the delegate's thing via the delagator                        #
# Because the PROCs of a STRUCT don't have an equivalent of e.g. Java's #
# "this", we have to explicitly pass the delegate as a parameter        #
PROC invoke thing = ( REF DELEGATOR delegator )STRING:
    # the following is Algol 68 for what would be written in Java as    #
    #                           "delegator.thing( delegator.delegate )" #
    ( thing OF delegator )( delegate OF delegator )
;

main:
(

    print( ( "No delegate           : "
           , invoke thing( new delegator( NIL ) )
           , newline
           , "Delegate with no thing: "
           , invoke thing( new delegator( new delegate( NIL ) ) )
           , newline
           , "Delegate with a thing : "
           , invoke thing( new delegator( new delegate( HEAP PROC STRING := STRING: ( "delegate implementation" ) ) ) )
           , newline
           )
         )

)


Utils.Helpers.pickNFrom(3,[1..7].walk())    // 35 combos
.filter(fcn(numbers){ numbers.sum(0)==12 }) // which all sum to 12 (==5)
.println();