public class LinePlaneIntersection {
    private static class Vector3D {
        private double x, y, z;

        Vector3D(double x, double y, double z) {
            this.x = x;
            this.y = y;
            this.z = z;
        }

        Vector3D plus(Vector3D v) {
            return new Vector3D(x + v.x, y + v.y, z + v.z);
        }

        Vector3D minus(Vector3D v) {
            return new Vector3D(x - v.x, y - v.y, z - v.z);
        }

        Vector3D times(double s) {
            return new Vector3D(s * x, s * y, s * z);
        }

        double dot(Vector3D v) {
            return x * v.x + y * v.y + z * v.z;
        }

        @Override
        public String toString() {
            return String.format("(%f, %f, %f)", x, y, z);
        }
    }

    private static Vector3D intersectPoint(Vector3D rayVector, Vector3D rayPoint, Vector3D planeNormal, Vector3D planePoint) {
        Vector3D diff = rayPoint.minus(planePoint);
        double prod1 = diff.dot(planeNormal);
        double prod2 = rayVector.dot(planeNormal);
        double prod3 = prod1 / prod2;
        return rayPoint.minus(rayVector.times(prod3));
    }

    public static void main(String[] args) {
        Vector3D rv = new Vector3D(0.0, -1.0, -1.0);
        Vector3D rp = new Vector3D(0.0, 0.0, 10.0);
        Vector3D pn = new Vector3D(0.0, 0.0, 1.0);
        Vector3D pp = new Vector3D(0.0, 0.0, 5.0);
        Vector3D ip = intersectPoint(rv, rp, pn, pp);
        System.out.println("The ray intersects the plane at " + ip);
    }
}


0010 FOR i#:=1 TO 100 DO
0020   IF i# MOD 15=0 THEN
0030     PRINT "FizzBuzz"
0040   ELIF i# MOD 5=0 THEN
0050     PRINT "Buzz"
0060   ELIF i# MOD 3=0 THEN
0070     PRINT "Fizz"
0080   ELSE
0090     PRINT i#
0100   ENDIF
0110 ENDFOR i#
0120 END


#!/usr/bin/perl -w
use DateTime ;

my @happymonths ;
my @workhardyears ;
my @longmonths = ( 1 , 3 , 5 , 7 , 8 , 10 , 12 ) ;
my @years = 1900..2100 ;
foreach my $year ( @years ) {
   my $countmonths = 0 ;
   foreach my $month ( @longmonths ) {
      my $dt = DateTime->new( year => $year ,
	                      month => $month ,
			      day   => 1 ) ;
      if ( $dt->day_of_week == 5 ) {
	 $countmonths++ ;
	 my $yearfound = $dt->year ;
	 my $monthfound = $dt->month_name ;
	 push ( @happymonths , "$yearfound  $monthfound" ) ;
      }
   }
   if ( $countmonths == 0 ) {
      push ( @workhardyears, $year ) ;
   }
}
print "There are " . @happymonths . " months with 5 full weekends!\n" ;
print "The first 5 and the last 5 of them are:\n" ;
foreach my $i ( 0..4 ) {
   print "$happymonths[ $i ]\n" ;
}
foreach my $i ( -5..-1 ) {
   print "$happymonths[ $i ]\n" ;
}
print "No long weekends in the following " . @workhardyears . " years:\n" ;
map { print "$_\n" } @workhardyears ;


# add as many as you please
def addVector:
  transpose | add;

# . - y
def minusVector(y):
  [.[0] - y[0], .[1] - y[1], .[2] - y[2]];

# scalar multiplication: . * s
def multVector(s):
    map(. * s);

def dot(y):
  .[0] * y[0] + .[1] * y[1] + .[2] * y[2];

def intersectPoint($rayVector; $rayPoint; $planeNormal; $planePoint):
  ($rayPoint | minusVector($planePoint)) as $diff
  | ($diff|dot($planeNormal)) as $prod1
  | ($rayVector|dot($planeNormal)) as $prod2
  | $rayPoint | minusVector($rayVector | multVector(($prod1 / $prod2) )) ;

def rv : [0, -1, -1];
def rp : [0,  0, 10];
def pn : [0,  0,  1];
def pp : [0,  0,  5];

"The ray intersects the plane at:",
intersectPoint(rv; rp; pn; pp)


function lineplanecollision(planenorm::Vector, planepnt::Vector, raydir::Vector, raypnt::Vector)
    ndotu = dot(planenorm, raydir)
    if ndotu ≈ 0 error("no intersection or line is within plane") end

    w  = raypnt - planepnt
    si = -dot(planenorm, w) / ndotu
    ψ  = w .+ si .* raydir .+ planepnt
    return ψ
end

# Define plane
planenorm = Float64[0, 0, 1]
planepnt  = Float64[0, 0, 5]

# Define ray
raydir = Float64[0, -1, -1]
raypnt = Float64[0,  0, 10]

ψ = lineplanecollision(planenorm, planepnt, raydir, raypnt)
println("Intersection at $ψ")


// version 1.1.51

class Vector3D(val x: Double, val y: Double, val z: Double) {

    operator fun plus(v: Vector3D) = Vector3D(x + v.x, y + v.y, z + v.z)

    operator fun minus(v: Vector3D) = Vector3D(x - v.x, y - v.y, z - v.z)

    operator fun times(s: Double) = Vector3D(s * x, s * y, s * z)

    infix fun dot(v: Vector3D) = x * v.x + y * v.y + z * v.z

    override fun toString() = "($x, $y, $z)"
}

fun intersectPoint(
    rayVector: Vector3D,
    rayPoint: Vector3D,
    planeNormal: Vector3D,
    planePoint: Vector3D
): Vector3D {
    val diff  = rayPoint - planePoint
    val prod1 = diff dot planeNormal
    val prod2 = rayVector dot planeNormal
    val prod3 = prod1 / prod2
    return rayPoint - rayVector * prod3
}

fun main(args: Array<String>) {
    val rv = Vector3D(0.0, -1.0, -1.0)
    val rp = Vector3D(0.0,  0.0, 10.0)
    val pn = Vector3D(0.0,  0.0,  1.0)
    val pp = Vector3D(0.0,  0.0,  5.0)
    val ip = intersectPoint(rv, rp, pn, pp)
    println("The ray intersects the plane at $ip")
}


fizzbuzz
  mod_three = 3
  mod_five = 5
  comefrom fizzbuzz
  n
  comefrom fizzbuzz if n is mod_three
  comefrom fizzbuzz if n is mod_five
  n = n + 1

  fizz
    comefrom fizzbuzz if n is mod_three
    'Fizz'...
    mod_three = mod_three + 3
    linebreak
      # would like to write "unless mod_three is mod_five"
      comefrom fizz if mod_three - mod_five - 3
      ''

  buzz
    comefrom fizzbuzz if n is mod_five
    'Buzz'
    mod_five = mod_five + 5

  comefrom fizzbuzz if n is 100


function make(xval, yval, zval)
    return {x=xval, y=yval, z=zval}
end

function plus(lhs, rhs)
    return make(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z)
end

function minus(lhs, rhs)
    return make(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z)
end

function times(lhs, scale)
    return make(scale * lhs.x, scale * lhs.y, scale * lhs.z)
end

function dot(lhs, rhs)
    return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z
end

function tostr(val)
    return "(" .. val.x .. ", " .. val.y .. ", " .. val.z .. ")"
end

function intersectPoint(rayVector, rayPoint, planeNormal, planePoint)
    diff = minus(rayPoint, planePoint)
    prod1 = dot(diff, planeNormal)
    prod2 = dot(rayVector, planeNormal)
    prod3 = prod1 / prod2
    return minus(rayPoint, times(rayVector, prod3))
end

rv = make(0.0, -1.0, -1.0)
rp = make(0.0, 0.0, 10.0)
pn = make(0.0, 0.0, 1.0)
pp = make(0.0, 0.0, 5.0)
ip = intersectPoint(rv, rp, pn, pp)
print("The ray intersects the plane at " .. tostr(ip))


geom3d:-plane(P, [geom3d:-point(p1,0,0,5), [0,0,1]]);
geom3d:-line(L, [geom3d:-point(p2,0,0,10), [0,-1,-1]]);
geom3d:-intersection(px,L,P);
geom3d:-detail(px);


(defun fizzbuzz ()
  (loop for x from 1 to 100 do
    (princ (cond ((zerop (mod x 15)) "FizzBuzz")
                 ((zerop (mod x 3))  "Fizz")
                 ((zerop (mod x 5))  "Buzz")
                 (t                  x)))
    (terpri)))


with javascript_semantics
sequence m31 = {"January",0,"March",0,"May",0,"July","August",0,"October",0,"December"}
integer y,m,
        nmonths = 0
string months
sequence res = {},
         none = {}

for y=1900 to 2100 do
    months = ""
    for m=1 to 12 do
        if string(m31[m])
        and day_of_week(y,m,1,true)="Friday" then
            if length(months)!=0 then months &= ", " end if
            months &= m31[m]
            nmonths += 1
        end if
    end for
    if length(months)=0 then
        none = append(none,y)
    else
        res = append(res,sprintf("%d : %s\n",{y,months}))
    end if
end for

printf(1,"Found %d months with five full weekends\n",nmonths)
res[6..-6] = {" ...\n"}
puts(1,join(res,""))
printf(1,"Found %d years with no month having 5 weekends:\n",{length(none)})
none[6..-6] = {".."}
?none


function point = intersectPoint(rayVector, rayPoint, planeNormal, planePoint)

pdiff = rayPoint - planePoint;
prod1 = dot(pdiff, planeNormal);
prod2 = dot(rayVector, planeNormal);
prod3 = prod1 / prod2;

point = rayPoint - rayVector * prod3;


MODULE LinePlane;
FROM RealStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;

TYPE
    Vector3D = RECORD
        x,y,z : REAL;
    END;

PROCEDURE Minus(lhs,rhs : Vector3D) : Vector3D;
VAR out : Vector3D;
BEGIN
    RETURN Vector3D{lhs.x-rhs.x, lhs.y-rhs.y, lhs.z-rhs.z};
END Minus;

PROCEDURE Times(a : Vector3D; s : REAL) : Vector3D;
BEGIN
    RETURN Vector3D{a.x*s, a.y*s, a.z*s};
END Times;

PROCEDURE Dot(lhs,rhs : Vector3D) : REAL;
BEGIN
    RETURN lhs.x*rhs.x + lhs.y*rhs.y + lhs.z*rhs.z;
END Dot;

PROCEDURE ToString(self : Vector3D);
VAR buf : ARRAY[0..63] OF CHAR;
BEGIN
    WriteString("(");
    RealToStr(self.x,buf);
    WriteString(buf);
    WriteString(", ");
    RealToStr(self.y,buf);
    WriteString(buf);
    WriteString(", ");
    RealToStr(self.z,buf);
    WriteString(buf);
    WriteString(")");
END ToString;

PROCEDURE IntersectPoint(rayVector,rayPoint,planeNormal,planePoint : Vector3D) : Vector3D;
VAR
    diff : Vector3D;
    prod1,prod2,prod3 : REAL;
BEGIN
    diff := Minus(rayPoint,planePoint);
    prod1 := Dot(diff, planeNormal);
    prod2 := Dot(rayVector, planeNormal);
    prod3 := prod1 / prod2;
    RETURN Minus(rayPoint, Times(rayVector, prod3));
END IntersectPoint;

VAR ip : Vector3D;
BEGIN
    ip := IntersectPoint(Vector3D{0.0,-1.0,-1.0},Vector3D{0.0,0.0,10.0},Vector3D{0.0,0.0,1.0},Vector3D{0.0,0.0,5.0});

    WriteString("The ray intersects the plane at ");
    ToString(ip);
    WriteLn;

    ReadChar;
END LinePlane.


Require Import Coq.Lists.List.
(* https://coq.inria.fr/library/Coq.Lists.List.html *)

Require Import Coq.Strings.String.
(* https://coq.inria.fr/library/Coq.Strings.String.html *)

Require Import Coq.Strings.Ascii.
(* https://coq.inria.fr/library/Coq.Strings.Ascii.html *)

Require Import Coq.Init.Nat.
(* https://coq.inria.fr/library/Coq.Init.Nat.html *)

(** Definition of [string_of_nat] to convert natural numbers to strings. *)

Definition ascii_of_digit (n: nat): ascii :=
  ascii_of_nat (n + 48).

Definition is_digit (n: nat): bool :=
  andb (0 <=? n) (n <=? 9).

Fixpoint rec_string_of_nat (counter: nat) (n: nat) (acc: string): string :=
  match counter with
    | 0 => EmptyString
    | S c =>
      if (is_digit n)
      then String (ascii_of_digit n) acc
      else rec_string_of_nat c (n / 10) (String (ascii_of_digit (n mod 10)) acc)
  end.
(** The counter is only used to ensure termination. *)

Definition string_of_nat (n: nat): string :=
  rec_string_of_nat n n EmptyString.

(** The FizzBuzz problem. *)

Definition fizz: string :=
  "Fizz" .

Definition buzz: string :=
  "Buzz" .

Definition new_line: string :=
  String (ascii_of_nat 10) EmptyString.

Definition is_divisible_by (n: nat) (k: nat): bool :=
  (n mod k) =? 0.

Definition get_fizz_buzz_term (n: nat): string :=
  if (is_divisible_by n 15) then fizz ++ buzz
  else if (is_divisible_by n 3) then fizz
  else if (is_divisible_by n 5) then buzz
  else (string_of_nat n).

Definition get_first_positive_numbers (n: nat): list nat :=
  seq 1 n.

Definition fizz_buzz_terms (n: nat): list string :=
  map get_fizz_buzz_term (get_first_positive_numbers n).

Definition fizz_buzz: string :=
  concat new_line (fizz_buzz_terms 100).

(** This shows the string. *)
Eval compute in fizz_buzz.


go ?=>
  println("Months with five weekends:"),
  FiveWeekends = [ [Year,Month] : Year in 1900..2100, Month in [1,3,5,7,8,10,12], dow(Year,Month,1) == 5],
  WLen = FiveWeekends.len,
  println(take(FiveWeekends,5)),
  println("..."),
  println(drop(FiveWeekends,WLen-5)),
  println(len=WLen),
  nl,

  println("Years w/o five weekends:"),
  FiveWeekendYears = [Year : [Year,_] in FiveWeekends].remove_dups,
  NoHitYears = [Year : Year in 1900..2100, not member(Year,FiveWeekendYears)],
  NHLen = NoHitYears.len,
  println(take(NoHitYears,5)),
  println("..."),
  println(drop(NoHitYears,NHLen-5)),
  println(len=NHLen),
  nl.
go => true.

% Day of week, Sakamoto's method
dow(Y, M, D) = R =>
  T = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4],
  if M < 3 then
     Y := Y - 1
  end,
  R = (Y + Y // 4 - Y // 100 + Y // 400 + T[M] + D) mod 7.

% Days in a month.
max_days_in_month(Year,Month) = Days =>
  if member(Month, [1,3,5,7,8,10,12]) then
    Days = 31
  elseif member(Month,[4,6,9,11]) then
    Days = 30
  else
    if leap_year(Year) then
     Days = 29
   else
     Days = 28
   end
  end.

leap_year(Year) =>
  (Year mod 4 == 0, Year mod 100 != 0)
  ;
  Year mod 400 == 0.


(setq Lst
   (make
      (for Y (range 1900 2100)
         (for M (range 1 12)
            (and
               (date Y M 31)
               (= "Friday" (day (date Y M 1)))
               (link (list (get *Mon M) Y)) ) ) ) ) )

(prinl "There are " (length Lst) " months with five weekends:")
(mapc println (head 5 Lst))
(prinl "...")
(mapc println (tail 5 Lst))
(prinl)
(setq Lst (diff (range 1900 2100) (uniq (mapcar cadr Lst))))
(prinl "There are " (length Lst) " years with no five-weekend months:")
(println Lst)


int(0..1) weekends(object day)
{
    return (<5,6,7>)[day->week_day()];
}

int(0..1) has5(object month)
{
    return sizeof(filter(month->days(), weekends))==15;
}

object range = Calendar.Year(1900)->distance(Calendar.Year(2101));
array have5 = filter(range->months(), has5);

write("found %d months:\n%{%s\n%}...\n%{%s\n%}",
       sizeof(have5), have5[..4]->format_nice(), have5[<4..]->format_nice());

array rest = range->years() - have5->year();
write("%d years without any 5 weekend month:\n %{%d,%}\n", sizeof(rest), rest->year_no());


type Vector = tuple[x, y, z: float]

func `+`(v1, v2: Vector): Vector =
  ## Add two vectors.
  (v1.x + v2.x, v1.y + v2.y, v1.z + v2.z)

func `-`(v1, v2: Vector): Vector =
  ## Subtract a vector to another one.
  (v1.x - v2.x, v1.y - v2.y, v1.z - v2.z)

func `*`(v1, v2: Vector): float =
  ## Compute the dot product of two vectors.
  v1.x * v2.x + v1.y * v2.y + v1.z * v2.z

func `*`(v: Vector; k: float): Vector =
  ## Multiply a vector by a scalar.
  (v.x * k, v.y * k, v.z * k)

func intersection(lineVector, linePoint, planeVector, planePoint: Vector): Vector =
  ## Return the coordinates of the intersection of two vectors.

  let tnum = planeVector * (planePoint - linePoint)
  let tdenom = planeVector * lineVector
  if tdenom == 0: return (Inf, Inf, Inf)  # No intersection.
  let t = tnum / tdenom
  result = lineVector * t + linePoint

let coords = intersection(lineVector = (0.0, -1.0, -1.0),
                          linePoint = (0.0, 0.0, 10.0),
                          planeVector = (0.0, 0.0, 1.0),
                          planePoint = (0.0, 0.0, 5.0))
echo "Intersection at ", coords


package  Line; sub new { my ($c, $a) = @_; my $self = { P0 => $a->{P0}, u => $a->{u} } } # point / ray
package Plane; sub new { my ($c, $a) = @_; my $self = { V0 => $a->{V0}, n => $a->{n} } } # point / normal

package main;

sub dot { my $p; $p    += $_[0][$_] * $_[1][$_] for 0[email protected]{$_[0]}-1; $p } # dot product
sub vd  { my @v; $v[$_] = $_[0][$_] - $_[1][$_] for 0[email protected]{$_[0]}-1; @v } # vector difference
sub va  { my @v; $v[$_] = $_[0][$_] + $_[1][$_] for 0[email protected]{$_[0]}-1; @v } # vector addition
sub vp  { my @v; $v[$_] = $_[0][$_] * $_[1][$_] for 0[email protected]{$_[0]}-1; @v } # vector product

sub line_plane_intersection {
    my($L, $P) = @_;

    my $cos = dot($L->{u}, $P->{n});     # cosine between normal & ray
    return 'Vectors are orthogonol; no intersection or line within plane' if $cos == 0;

    my @W = vd($L->{P0},$P->{V0});       # difference between P0 and V0
    my $SI = -dot($P->{n}, \@W) / $cos;  # line segment where it intersets the plane

    my @a = vp($L->{u},[($SI)x3]);
    my @b = va($P->{V0},\@a);
    va(\@W,\@b);
}

my $L =  Line->new({ P0=>[0,0,10], u=>[0,-1,-1]});
my $P = Plane->new({ V0=>[0,0,5 ], n=>[0, 0, 1]});
print 'Intersection at point: ', join(' ', line_plane_intersection($L, $P)) . "\n";


include "cowgol.coh";

var i: uint8 := 1;
while i <= 100 loop
    if i % 15 == 0 then
        print("FizzBuzz");
    elseif i % 5 == 0 then
        print("Buzz");
    elseif i % 3 == 0 then
        print("Fizz");
    else
        print_i8(i);
    end if;
    print_nl();
    i := i + 1;
end loop;


weekends: procedure options (main); /* 28/11/2011 */
   declare tally fixed initial (0);
   declare (d, dend, dn) fixed (10);
   declare (date_start, date_end) picture '99999999';
   declare Leap fixed (1);

   date_start = '01011900';
   do date_start = date_start to '01012100';
      d        = days(date_start, 'DDMMYYYY');
      date_end = date_start + 30110000;
      dend     = days(date_end,   'DDMMYYYY');
      Leap     = dend-d-364;
      do dn = d, d+59+Leap, d+120+Leap, d+181+Leap, d+212+Leap,
                 d+273+Leap, d+334+Leap;
         if weekday(dn) = 6 then
            do;
               put skip list (daystodate(dn, 'MmmYYYY') || ' has 5 weekends' );
               tally = tally + 1;
            end;
      end;
   end;

   put skip list ('Total number of months having 3-day weekends =', tally);

end weekends;


$fiveWeekends = @()
$yearsWithout = @()
foreach ($y in 1900..2100) {
  $hasFiveWeekendMonth = $FALSE
  foreach ($m in @("01","03","05","07","08",10,12)) {
    if ((Get-Date "$y-$m-1").DayOfWeek -eq "Friday") {
      $fiveWeekends += "$y-$m"
      $hasFiveWeekendMonth = $TRUE
    }
  }
  if ($hasFiveWeekendMonth -eq $FALSE) {
     $yearsWithout += $y
  }
}
Write-Output "Between the years 1900 and 2100, inclusive, there are $($fiveWeekends.count) months with five full weekends:"
Write-Output "$($fiveWeekends[0..4] -join ","),...,$($fiveWeekends[-5..-1] -join ",")"

Write-Output ""
Write-Output "Extra Credit: these $($yearsWithout.count) years have no such month:"
Write-Output ($yearsWithout -join ",")


with javascript_semantics
function dot(sequence a, b) return sum(sq_mul(a,b)) end function

function intersection_point(sequence line_vector,line_point,plane_normal,plane_point)
    atom a = dot(line_vector,plane_normal)
    if a=0 then return "no intersection" end if
    sequence diff = sq_sub(line_point,plane_point)
    return sq_add(sq_add(diff,plane_point),sq_mul(-dot(diff,plane_normal)/a,line_vector))
end function

?intersection_point({0,-1,-1},{0,0,10},{0,0,1},{0,0,5})
?intersection_point({3,2,1},{0,2,4},{1,2,3},{3,3,3})
?intersection_point({1,1,0},{0,0,1},{0,0,3},{0,0,0}) -- (parallel to plane)
?intersection_point({1,1,0},{1,1,0},{0,0,3},{0,0,0}) -- (line within plane)


plus(U, V) = {U[1] + V[1], U[2] + V[2], U[3] + V[3]}.

minus(U, V) = {U[1] - V[1], U[2] - V[2], U[3] - V[3]}.

times(U, S) = {U[1] * S, U[2] * S, U[3] * S}.

dot(U, V) = U[1] * V[1] + U[2] * V[2] + U[3] * V[3].

intersect_point(RayVector, RayPoint, PlaneNormal, PlanePoint) = IntersectPoint =>
    Diff = minus(RayPoint, PlanePoint),
    Prod1 = dot(Diff, PlaneNormal),
    Prod2 = dot(RayVector, PlaneNormal),
    Prod3 = Prod1 / Prod2,
    IntersectPoint = minus(RayPoint, times(RayVector, Prod3)).

main =>
    RayVector = {0.0, -1.0, -1.0},
    RayPoint = {0.0, 0.0, 10.0},
    PlaneNormal = {0.0, 0.0, 1.0},
    PlanePoint = {0.0, 0.0, 5.0},
    IntersectPoint = intersect_point(RayVector, RayPoint, PlaneNormal, PlanePoint),
    printf("The ray intersects the plane at (%f, %f, %f)\n",
        IntersectPoint[1],
        IntersectPoint[2],
        IntersectPoint[3]
    ).


1.upto(100) do |v|
  p fizz_buzz(v)
end

def fizz_buzz(value)
  word = ""
  word += "fizz" if value % 3 == 0
  word += "buzz" if value % 5 == 0
  word += value.to_s if word.empty?
  word
end


main() :-
    weekends(1900, 2100, FiveWeekendList, RemainderWeekendList),

    length(FiveWeekendList, FiveLen),
    maplist(write, ["Total five weekend months:", FiveLen, '\n']),

    slice(FiveWeekendList, 5, FirstFiveList),
    maplist(write, ["First five {year,month} pairs:", FirstFiveList, '\n']),

    slice(FiveWeekendList, -5, LastFiveList),
    maplist(write, ["Last five {year,month} pairs:", LastFiveList, '\n']),

    maplist(take_year, FiveWeekendList, FiveYearList),
    list_to_set(FiveYearList, FiveYearSet),

    maplist(take_year, RemainderWeekendList, RemainderYearList),
    list_to_set(RemainderYearList, RemainderYearSet),

    subtract(RemainderYearSet, FiveYearSet, NonFiveWeekendSet),
    length(NonFiveWeekendSet, NonFiveWeekendLen),

    maplist(write, ["Total years with no five weekend months:", NonFiveWeekendLen, '\n']),
    writeln(NonFiveWeekendSet).

weekends(StartYear, EndYear, FiveWeekendList, RemainderWeekendList) :-
    numlist(StartYear, EndYear, YearList),
    numlist(1, 12, MonthList),
    pair(YearList, MonthList, YearMonthList),
    partition(has_five_weekends, YearMonthList, FiveWeekendList, RemainderWeekendList).

has_five_weekends({Year, Month}) :-
    long_month(Month),
    starts_on_a_friday(Year, Month).

starts_on_a_friday(Year, Month) :-
    Date = date(Year, Month, 1),
    day_of_the_week(Date, DayOfTheWeek),
    DayOfTheWeek == 5.

take_year({Year, _}, Year).

long_month(1).
long_month(3).
long_month(5).
long_month(7).
long_month(8).
long_month(10).
long_month(12).

% Helpers

% https://stackoverflow.com/a/7739806
pair(L1, L2, Pairs):-findall({A,B}, (member(A, L1), member(B, L2)), Pairs).

slice(_, 0, []).

slice(List, N, NList):-
    N < 0,
    N1 is abs(N),
    last_n_elements(List, N1, NList).

slice(List, N, NList):-
    N > 0,
    first_n_elements(List, N, NList).

first_n_elements(List, N, FirstN):-
    length(FirstN, N),
    append(FirstN, _, List).

last_n_elements(List, N, LastN) :-
    length(LastN, N),
    append(_, LastN, List).


:- initialization(main).

vector_plus(U, V, W) :-
    U = p(X1, Y1, Z1),
    V = p(X2, Y2, Z2),
    X3 is X1 + X2,
    Y3 is Y1 + Y2,
    Z3 is Z1 + Z2,
    W = p(X3, Y3, Z3).

vector_minus(U, V, W) :-
    U = p(X1, Y1, Z1),
    V = p(X2, Y2, Z2),
    X3 is X1 - X2,
    Y3 is Y1 - Y2,
    Z3 is Z1 - Z2,
    W = p(X3, Y3, Z3).

vector_times(U, S, V) :-
    U = p(X1, Y1, Z1),
    X2 is X1 * S,
    Y2 is Y1 * S,
    Z2 is Z1 * S,
    V = p(X2, Y2, Z2).

vector_dot(U, V, S) :-
    U = p(X1, Y1, Z1),
    V = p(X2, Y2, Z2),
    S is X1 * X2 + Y1 * Y2 + Z1 * Z2.

intersect_point(RayVector, RayPoint, PlaneNormal, PlanePoint, IntersectPoint) :-
    vector_minus(RayPoint, PlanePoint, Diff),
    vector_dot(Diff, PlaneNormal, Prod1),
    vector_dot(RayVector, PlaneNormal, Prod2),
    Prod3 is Prod1 / Prod2,
    vector_times(RayVector, Prod3, Times),
    vector_minus(RayPoint, Times, IntersectPoint).

main :-
    RayVector = p(0.0, -1.0, -1.0),
    RayPoint = p(0.0, 0.0, 10.0),
    PlaneNormal = p(0.0, 0.0, 1.0),
    PlanePoint = p(0.0, 0.0, 5.0),
    intersect_point(RayVector, RayPoint, PlaneNormal, PlanePoint, p(X, Y, Z)),
    format("The ray intersects the plane at (~f, ~f, ~f)\n", [X, Y, Z]).


Procedure DateG(year.w, month.b, day)
  ;Returns the number of days before or after the earliest reference date
  ;in PureBasic's Date Library (1 Jan 1970) based on an assumed Gregorian calendar calculation
  Protected days
  days = (year) * 365 + (month - 1) * 31 + day - 1 - 719527 ;DAYS_UNTIL_1970_01_01 = 719527
  If month >= 3
    days - Int(0.4 * month + 2.3)
  Else
    year - 1
  EndIf
  days + Int(year/4) - Int(year/100) + Int(year/400)

  ProcedureReturn days
EndProcedure

Procedure startsOnFriday(year, month)
  ;0 is Sunday, 1 is Monday, ... 5 is Friday, 6 is Saturday
  Protected referenceDay = DayOfWeek(Date(1970, 1, 1, 0, 0, 0)) ;link to the first day in the PureBasic's date library
  Protected resultDay = (((DateG(year, month, 1) + referenceDay) % 7) + 7) % 7
   If resultDay = 5
    ProcedureReturn #True
  EndIf
EndProcedure

Procedure has31Days(month)
  Select month
    Case 1, 3, 5, 7 To 8, 10, 12
      ProcedureReturn #True
  EndSelect
EndProcedure

Procedure checkMonths(year)
  Protected month, count
  For month = 1 To 12
    If startsOnFriday(year, month) And has31Days(month)
      count + 1
      PrintN(Str(year) + " " + Str(month))
    EndIf
  Next
  ProcedureReturn count
EndProcedure

Procedure fiveWeekends()
  Protected startYear = 1900, endYear = 2100, year, monthTotal, total
  NewList yearsWithoutFiveWeekends()

  For year = startYear To endYear
    monthTotal = checkMonths(year)
    total + monthTotal
    ;extra credit
    If monthTotal = 0
      AddElement(yearsWithoutFiveWeekends())
      yearsWithoutFiveWeekends() = year
    EndIf
  Next

   PrintN("Total number of months: " + Str(total) + #CRLF$)
   PrintN("Years with no five-weekend months: " + Str(ListSize(yearsWithoutFiveWeekends())) )
EndProcedure

If OpenConsole()
  fiveWeekends()

  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
  CloseConsole()
EndIf


#!/bin/python
from __future__ import print_function
import numpy as np

def LinePlaneCollision(planeNormal, planePoint, rayDirection, rayPoint, epsilon=1e-6):

	ndotu = planeNormal.dot(rayDirection)
	if abs(ndotu) < epsilon:
		raise RuntimeError("no intersection or line is within plane")

	w = rayPoint - planePoint
	si = -planeNormal.dot(w) / ndotu
	Psi = w + si * rayDirection + planePoint
	return Psi

if __name__=="__main__":
	#Define plane
	planeNormal = np.array([0, 0, 1])
	planePoint = np.array([0, 0, 5]) #Any point on the plane

	#Define ray
	rayDirection = np.array([0, -1, -1])
	rayPoint = np.array([0, 0, 10]) #Any point along the ray

	Psi = LinePlaneCollision(planeNormal, planePoint, rayDirection, rayPoint)
	print ("intersection at", Psi)


intersect_point <- function(ray_vec, ray_point, plane_normal, plane_point) {

  pdiff <- ray_point - plane_point
  prod1 <- pdiff %*% plane_normal
  prod2 <- ray_vec %*% plane_normal
  prod3 <- prod1 / prod2
  point <- ray_point - ray_vec * as.numeric(prod3)

  return(point)
}


#lang racket
;; {{trans|Sidef}}
;; vectors are represented by lists

(struct Line (P0 u⃗))

(struct Plane (V0 n⃗))

(define (· a b) (apply + (map * a b)))

(define (line-plane-intersection L P)
  (match-define (cons (Line P0 u⃗) (Plane V0 n⃗)) (cons L P))
  (define cos (· n⃗ u⃗))
  (when (zero? cos) (error "vectors are orthoganal"))
  (define W (map - P0 V0))
  (define *SI (let ((SI (- (/ (· n⃗ W) cos)))) (λ (n) (* SI n))))
  (map + W (map *SI u⃗) V0))

(module+ test
  (require rackunit)
  (check-equal?
   (line-plane-intersection (Line '(0 0 10) '(0 -1 -1))
                            (Plane '(0 0 5) '(0 0 1)))
   '(0 -5 5)))


alias fizzbuzz [
	loop i 100 [
		push i (+ $i 1) [
			cond (! (mod $i 15)) [
				echo FizzBuzz
			] (! (mod $i 3)) [
				echo Fizz
			] (! (mod $i 5)) [
				echo Buzz
			] [
				echo $i
			]
		]
	]
]


from datetime import timedelta, date

DAY     = timedelta(days=1)
START, STOP = date(1900, 1, 1), date(2101, 1, 1)
WEEKEND = {6, 5, 4}     # Sunday is day 6
FMT     = '%Y %m(%B)'

def fiveweekendspermonth(start=START, stop=STOP):
    'Compute months with five weekends between dates'

    when = start
    lastmonth = weekenddays = 0
    fiveweekends = []
    while when < stop:
        year, mon, _mday, _h, _m, _s, wday, _yday, _isdst = when.timetuple()
        if mon != lastmonth:
            if weekenddays >= 15:
                fiveweekends.append(when - DAY)
            weekenddays = 0
            lastmonth = mon
        if wday in WEEKEND:
            weekenddays += 1
        when += DAY
    return fiveweekends

dates = fiveweekendspermonth()
indent = '  '
print('There are %s months of which the first and last five are:' % len(dates))
print(indent +('\n'+indent).join(d.strftime(FMT) for d in dates[:5]))
print(indent +'...')
print(indent +('\n'+indent).join(d.strftime(FMT) for d in dates[-5:]))

print('\nThere are %i years in the range that do not have months with five weekends'
      % len(set(range(START.year, STOP.year)) - {d.year for d in dates}))


  [ over 3 < if [ 1 - ]
    dup 4 / over +
    over 100 / -
    swap 400 / +
    swap 1 -
    [ table
      0 3 2 5 0 3
      5 1 4 6 2 4 ]
    + + 7 mod ]                     is dayofweek ( day month year --> weekday )

  [ 1 -
    [ table
      $ "January"   $ "February"
      $ "March"     $ "April"
      $ "May"       $ "June"
      $ "July"      $ "August"
      $ "September" $ "October"
      $ "November"  $ "December" ]
    do ]                            is monthname (   monthnumber --> $        )

  [] [] temp put
  201 times
    [ true temp put
      i^ 1900 +
      ' [ 1 3 5 7 8 10 12 ]
      witheach
        [ 2dup swap
          1 unrot dayofweek
          5 = iff
            [ false temp replace
              over join nested
              swap dip join ]
          else drop ]
      temp take iff
        [ temp take
          swap join
          temp put ]
      else drop ]
  temp take swap
  say "There are "
  dup size echo
  say " months with five weekends."
  cr cr
  5 split swap
  say "Five weekends: "
  witheach
    [ do swap
      monthname echo$
      sp echo
      i if say ", " ]
  cr say "               ..."
  cr space 15 of echo$
  -5 split nip
  witheach
    [ do swap
      monthname echo$
      sp echo
      i if say ", " ]
  cr cr
  say "Years without five weekends: "
  witheach
    [ echo
      i if say ", "
      i^ 8 mod 7 = if
        [ cr space 29 of echo$ ] ]


class Line {
    has $.P0; # point
    has $.u⃗;  # ray
}
class Plane {
    has $.V0; # point
    has $.n⃗;  # normal
}

sub infix:<∙> ( @a, @b where +@a == +@b ) { [+] @a «*» @b } # dot product

sub line-plane-intersection ($𝑳, $𝑷) {
    my $cos = $𝑷.n⃗ ∙ $𝑳.u⃗; # cosine between normal & ray
    return 'Vectors are orthogonal; no intersection or line within plane'
      if $cos == 0;
    my $𝑊 = $𝑳.P0 «-» $𝑷.V0;      # difference between P0 and V0
    my $S𝐼 = -($𝑷.n⃗ ∙ $𝑊) / $cos;  # line segment where it intersects the plane
    $𝑊 «+» $S𝐼 «*» $𝑳.u⃗ «+» $𝑷.V0; # point where line intersects the plane
 }

say 'Intersection at point: ', line-plane-intersection(
     Line.new( :P0(0,0,10), :u⃗(0,-1,-1) ),
    Plane.new( :V0(0,0, 5), :n⃗(0, 0, 1) )
  );


/* REXX */
Parse Value '0 0 1' With n.1 n.2 n.3   /* Normal Vector of the plane */
Parse Value '0 0 5' With p.1 p.2 p.3   /* Point in the plane         */
Parse Value '0 0 10' With a.1 a.2 a.3  /* Point of the line          */
Parse Value '0 -1 -1' With v.1 v.2 v.3 /* Vector of the line         */

a=n.1
b=n.2
c=n.3
d=n.1*p.1+n.2*p.2+n.3*p.3  /* Parameter form of the plane */
Say a'*x +' b'*y +' c'*z =' d

t=(d-(a*a.1+b*a.2+c*a.3))/(a*v.1+b*v.2+c*v.3)

x=a.1+t*v.1
y=a.2+t*v.2
z=a.3+t*v.3

Say 'Intersection: P('||x','y','z')'


import std.stdio, std.algorithm, std.conv;

/// With if-else.
void fizzBuzz(in uint n) {
    foreach (immutable i; 1 .. n + 1)
        if (!(i % 15))
            "FizzBuzz".writeln;
        else if (!(i % 3))
            "Fizz".writeln;
        else if (!(i % 5))
            "Buzz".writeln;
        else
            i.writeln;
}

/// With switch case.
void fizzBuzzSwitch(in uint n) {
    foreach (immutable i; 1 .. n + 1)
        switch (i % 15) {
            case 0:
                "FizzBuzz".writeln;
                break;
            case 3, 6, 9, 12:
                "Fizz".writeln;
                break;
            case 5, 10:
                "Buzz".writeln;
                break;
            default:
                i.writeln;
        }
}

void fizzBuzzSwitch2(in uint n) {
    foreach (immutable i; 1 .. n + 1)
        (i % 15).predSwitch(
        0,       "FizzBuzz",
        3,       "Fizz",
        5,       "Buzz",
        6,       "Fizz",
        9,       "Fizz",
        10,      "Buzz",
        12,      "Fizz",
        /*else*/ i.text).writeln;
}

void main() {
    100.fizzBuzz;
    writeln;
    100.fizzBuzzSwitch;
    writeln;
    100.fizzBuzzSwitch2;
}


ms = as.Date(sapply(c(1, 3, 5, 7, 8, 10, 12),
    function(month) paste(1900:2100, month, 1, sep = "-")))
ms = format(sort(ms[weekdays(ms) == "Friday"]), "%b %Y")
message("There are ", length(ms), " months with five weekends.")
message("The first five: ", paste(ms[1:5], collapse = ", "))
message("The last five: ", paste(tail(ms, 5), collapse = ", "))


#lang racket
(require srfi/19)

(define long-months '(1 3 5 7 8 10 12))
(define days #(sun mon tue wed thu fri sat))

(define (week-day date)
  (vector-ref days (date-week-day date)))

(define (five-weekends-a-month start end)
  (for*/list ([year (in-range start (+ end 1))]
              [month long-months]
              [date (in-value (make-date 0 0 0 0 31 month year 0))]
              #:when (eq? (week-day date) 'sun))
    date))

(define weekends (five-weekends-a-month 1900 2100))
(define count (length weekends))

(displayln (~a "There are " count " months with five weekends."))
(displayln "The first five are: ")
(for ([w (take weekends 5)])
  (displayln (date->string w "~b ~Y")))
(displayln "The last five are: ")
(for ([w (drop weekends (- count 5))])
  (displayln (date->string w "~b ~Y")))


require "matrix"

def intersectPoint(rayVector, rayPoint, planeNormal, planePoint)
    diff = rayPoint - planePoint
    prod1 = diff.dot planeNormal
    prod2 = rayVector.dot planeNormal
    prod3 = prod1 / prod2
    return rayPoint - rayVector * prod3
end

def main
    rv = Vector[0.0, -1.0, -1.0]
    rp = Vector[0.0, 0.0, 10.0]
    pn = Vector[0.0, 0.0, 1.0]
    pp = Vector[0.0, 0.0, 5.0]
    ip = intersectPoint(rv, rp, pn, pp)
    puts "The ray intersects the plane at %s" % [ip]
end

main()


use std::ops::{Add, Div, Mul, Sub};

#[derive(Copy, Clone, Debug, PartialEq)]
struct V3<T> {
    x: T,
    y: T,
    z: T,
}

impl<T> V3<T> {
    fn new(x: T, y: T, z: T) -> Self {
        V3 { x, y, z }
    }
}

fn zip_with<F, T, U>(f: F, a: V3<T>, b: V3<T>) -> V3<U>
where
    F: Fn(T, T) -> U,
{
    V3 {
        x: f(a.x, b.x),
        y: f(a.y, b.y),
        z: f(a.z, b.z),
    }
}

impl<T> Add for V3<T>
where
    T: Add<Output = T>,
{
    type Output = Self;

    fn add(self, other: Self) -> Self {
        zip_with(<T>::add, self, other)
    }
}

impl<T> Sub for V3<T>
where
    T: Sub<Output = T>,
{
    type Output = Self;

    fn sub(self, other: Self) -> Self {
        zip_with(<T>::sub, self, other)
    }
}

impl<T> Mul for V3<T>
where
    T: Mul<Output = T>,
{
    type Output = Self;

    fn mul(self, other: Self) -> Self {
        zip_with(<T>::mul, self, other)
    }
}

impl<T> V3<T>
where
    T: Mul<Output = T> + Add<Output = T>,
{
    fn dot(self, other: Self) -> T {
        let V3 { x, y, z } = self * other;
        x + y + z
    }
}

impl<T> V3<T>
where
    T: Mul<Output = T> + Copy,
{
    fn scale(self, scalar: T) -> Self {
        self * V3 {
            x: scalar,
            y: scalar,
            z: scalar,
        }
    }
}

fn intersect<T>(
    ray_vector: V3<T>,
    ray_point: V3<T>,
    plane_normal: V3<T>,
    plane_point: V3<T>,
) -> V3<T>
where
    T: Add<Output = T> + Sub<Output = T> + Mul<Output = T> + Div<Output = T> + Copy,
{
    let diff = ray_point - plane_point;
    let prod1 = diff.dot(plane_normal);
    let prod2 = ray_vector.dot(plane_normal);
    let prod3 = prod1 / prod2;
    ray_point - ray_vector.scale(prod3)
}

fn main() {
    let rv = V3::new(0.0, -1.0, -1.0);
    let rp = V3::new(0.0, 0.0, 10.0);
    let pn = V3::new(0.0, 0.0, 1.0);
    let pp = V3::new(0.0, 0.0, 5.0);
    println!("{:?}", intersect(rv, rp, pn, pp));
}


object LinePLaneIntersection extends App {
  val (rv, rp, pn, pp) =
    (Vector3D(0.0, -1.0, -1.0), Vector3D(0.0, 0.0, 10.0), Vector3D(0.0, 0.0, 1.0), Vector3D(0.0, 0.0, 5.0))
  val ip = intersectPoint(rv, rp, pn, pp)

  def intersectPoint(rayVector: Vector3D,
                     rayPoint: Vector3D,
                     planeNormal: Vector3D,
                     planePoint: Vector3D): Vector3D = {
    val diff = rayPoint - planePoint
    val prod1 = diff dot planeNormal
    val prod2 = rayVector dot planeNormal
    val prod3 = prod1 / prod2
    rayPoint - rayVector * prod3
  }

  case class Vector3D(x: Double, y: Double, z: Double) {
    def +(v: Vector3D) = Vector3D(x + v.x, y + v.y, z + v.z)
    def -(v: Vector3D) = Vector3D(x - v.x, y - v.y, z - v.z)
    def *(s: Double) = Vector3D(s * x, s * y, s * z)
    def dot(v: Vector3D): Double = x * v.x + y * v.y + z * v.z
    override def toString = s"($x, $y, $z)"
  }

  println(s"The ray intersects the plane at $ip")
}


main() {
  for (int i = 1; i <= 100; i++) {
    List<String> out = [];
    if (i % 3 == 0)
      out.add("Fizz");
    if (i % 5 == 0)
      out.add("Buzz");
    print(out.length > 0 ? out.join("") : i);
  }
}


# A month has 5 weekends iff it has 31 days and starts on Friday.

my @years = 1900 .. 2100;
my @has31 = 1, 3, 5, 7, 8, 10, 12;
my @happy = ($_ when *.day-of-week == 5 for (@years X @has31).map(-> ($y, $m) { Date.new: $y, $m, 1 }));

say 'Happy month count:  ', +@happy;
say 'First happy months: ' ~ @happy[^5];
say 'Last  happy months: ' ~ @happy[*-5 .. *];
say 'Dreary years count: ',  @years - @happy».year.squish;


/*REXX program  finds  months  that contain  five weekends   (given a date range).      */
month. =31;  month.2=0                           /*month days;   February is skipped.   */
month.4=30;  month.6=30; month.9=30; month.11=30 /*all the  months with  thirty-days.   */
parse arg yStart yStop .                         /*get the  "start"  and  "stop"  years.*/
if yStart=='' | yStart==","  then yStart= 1900   /*Not specified?  Then use the default.*/
if yStop =='' | yStop ==","  then yStop = 2100   /* "      "         "   "   "     "    */
years=yStop - yStart + 1                         /*calculate the number of yrs in range.*/
haps=0                                           /*number of five weekends happenings.  */
!.=0;                 @5w= 'five-weekend months' /*flag if a year has any five-weekends.*/
       do y=yStart to yStop                      /*process the years specified.         */
           do m=1  for 12;    wd.=0              /*process each month and also each year*/
                 do d=1  for month.m;  dat_= y"-"right(m,2,0)'-'right(d,2,0)
                 parse  upper  value   date('W', dat_, "I")    with    ? 3
                 wd.?=wd.?+1                     /*?  is the first two chars of weekday.*/
                 end   /*d*/                     /*WD.su = number of Sundays in a month.*/
           if wd.su\==5 | wd.fr\==5 | wd.sa\==5 then iterate           /*five weekends ?*/
           say 'There are five weekends in'   y   date('M', dat_, "I")
           haps=haps+1;   !.y=1                  /*bump counter; indicate yr has 5 WE's.*/
           end         /*m*/
       end             /*y*/
say
say "There were "  haps ' occurrence's(haps) "of"  @5w 'in year's(years)  yStart"──►"yStop
say; #=0
          do y=yStart  to yStop;   if !.y  then iterate                    /*skip if OK.*/
          #=#+1;        say  'Year '    y    " doesn't have any" @5wem'.'
          end   /*y*/
say
say  "There are "  # ' year's(#) "that haven't any" @5w 'in year's(years) yStart'──►'yStop
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
s: if arg(1)==1  then return arg(3);      return word(arg(2) 's',1)        /*pluralizer.*/


struct Line {
    P0,       # point
    u⃗,        # ray
}

struct Plane {
    V0,       # point
    n⃗,        # normal
}

func dot_prod(a, b) { a »*« b -> sum }

func line_plane_intersection(𝑳, 𝑷) {
    var cos = dot_prod(𝑷.n⃗, 𝑳.u⃗) ->
     || return 'Vectors are orthogonal'
    var 𝑊 = (𝑳.P0 »-« 𝑷.V0)
    var S𝐼 = -(dot_prod(𝑷.n⃗, 𝑊) / cos)
    𝑊 »+« (𝑳.u⃗ »*» S𝐼) »+« 𝑷.V0
}

say ('Intersection at point: ', line_plane_intersection(
         Line(P0: [0,0,10], u⃗: [0,-1,-1]),
        Plane(V0: [0,0, 5], n⃗: [0, 0, 1]),
))


Module Module1

    Class Vector3D
        Private ReadOnly x As Double
        Private ReadOnly y As Double
        Private ReadOnly z As Double

        Sub New(nx As Double, ny As Double, nz As Double)
            x = nx
            y = ny
            z = nz
        End Sub

        Public Function Dot(rhs As Vector3D) As Double
            Return x * rhs.x + y * rhs.y + z * rhs.z
        End Function

        Public Shared Operator +(ByVal a As Vector3D, ByVal b As Vector3D) As Vector3D
            Return New Vector3D(a.x + b.x, a.y + b.y, a.z + b.z)
        End Operator

        Public Shared Operator -(ByVal a As Vector3D, ByVal b As Vector3D) As Vector3D
            Return New Vector3D(a.x - b.x, a.y - b.y, a.z - b.z)
        End Operator

        Public Shared Operator *(ByVal a As Vector3D, ByVal b As Double) As Vector3D
            Return New Vector3D(a.x * b, a.y * b, a.z * b)
        End Operator

        Public Overrides Function ToString() As String
            Return String.Format("({0:F}, {1:F}, {2:F})", x, y, z)
        End Function
    End Class

    Function IntersectPoint(rayVector As Vector3D, rayPoint As Vector3D, planeNormal As Vector3D, planePoint As Vector3D) As Vector3D
        Dim diff = rayPoint - planePoint
        Dim prod1 = diff.Dot(planeNormal)
        Dim prod2 = rayVector.Dot(planeNormal)
        Dim prod3 = prod1 / prod2
        Return rayPoint - rayVector * prod3
    End Function

    Sub Main()
        Dim rv = New Vector3D(0.0, -1.0, -1.0)
        Dim rp = New Vector3D(0.0, 0.0, 10.0)
        Dim pn = New Vector3D(0.0, 0.0, 1.0)
        Dim pp = New Vector3D(0.0, 0.0, 5.0)
        Dim ip = IntersectPoint(rv, rp, pn, pp)
        Console.WriteLine("The ray intersects the plane at {0}", ip)
    End Sub

End Module


V perms = [‘ABCD’, ‘CABD’, ‘ACDB’, ‘DACB’, ‘BCDA’, ‘ACBD’, ‘ADCB’, ‘CDAB’,
           ‘DABC’, ‘BCAD’, ‘CADB’, ‘CDBA’, ‘CBAD’, ‘ABDC’, ‘ADBC’, ‘BDCA’,
           ‘DCBA’, ‘BACD’, ‘BADC’, ‘BDAC’, ‘CBDA’, ‘DBCA’, ‘DCAB’]

V missing = ‘’
L(i) 4
   V cnt = [0] * 4
   L(j) 0 .< perms.len
      cnt[perms[j][i].code - ‘A’.code]++
   L(j) 4
      I cnt[j] != factorial(4-1)
         missing ‘’= Char(code' ‘A’.code + j)
         L.break

print(missing)


[[Fizz]P 1 sw]sF
[[Buzz]P 1 sw]sB
[li p sz]sN
[[
]P]sW
[
 0 sw         [w = 0]sz
 li 3 % 0 =F  [Fizz if 0 == i % 3]sz
 li 5 % 0 =B  [Buzz if 0 == i % 5]sz
 lw 0 =N      [print Number if 0 == w]sz
 lw 1 =W      [print neWline if 1 == w]sz
 li 1 + si    [i += 1]sz
 li 100 !<L   [continue Loop if 100 >= i]sz
]sL
1 si          [i = 1]sz
0 0 =L        [enter Loop]sz


sum = 0
month = list(12)
mo = [4,0,0,3,5,1,3,6,2,4,0,2]
mon = [31,28,31,30,31,30,31,31,30,31,30,31]
mont = ["January","February","March","April","May","June",
        "July","August","September","October","November","December"]
for year = 1900 to 2100
    if year < 2100 leap = year - 1900 else leap = year - 1904 ok
    m = ((year-1900)%7) + floor(leap/4) % 7
    oldsum = sum
    for n = 1 to 12
        month[n] = (mo[n] + m) % 7
        x = (month[n] + 1) % 7
        if x = 2 and mon[n] = 31 sum += 1 see "" + year + "-" + mont[n] + nl ok
    next
    if sum = oldsum see "" + year + "-" + "(none)" + nl ok
next
see "Total : " + sum + nl


require 'date'
# The only case where the month has 5 weekends is when the last day
# of the month falls on a Sunday and the month has 31 days.

LONG_MONTHS = [1,3,5,7,8,10,12]
YEARS       = (1900..2100).to_a

dates    = YEARS.product(LONG_MONTHS).map{|y, m| Date.new(y,m,31)}.select(&:sunday?)
years_4w = YEARS - dates.map(&:year)

puts "There are #{dates.size} months with 5 weekends from 1900 to 2100:"
puts dates.first(5).map {|d| d.strftime("%b %Y") }, "..."
puts dates.last(5).map {|d| d.strftime("%b %Y") }
puts "There are #{years_4w.size} years without months with 5 weekends:"
puts years_4w.join(", ")


class Vector3D {
    construct new(x, y, z) {
        _x = x
        _y = y
        _z = z
    }

    x { _x }
    y { _y }
    z { _z }

    +(v) { Vector3D.new(_x + v.x, _y + v.y, _z + v.z) }

    -(v) { Vector3D.new(_x - v.x, _y - v.y, _z - v.z) }

    *(s) { Vector3D.new(s * _x, s * _y, s * _z) }

    dot(v) { _x * v.x + _y * v.y + _z * v.z }

    toString { "(%(_x), %(_y), %(_z))" }
}

var intersectPoint = Fn.new { |rayVector, rayPoint, planeNormal, planePoint|
    var diff  = rayPoint - planePoint
    var prod1 = diff.dot(planeNormal)
    var prod2 = rayVector.dot(planeNormal)
    var prod3 = prod1 / prod2
    return rayPoint - rayVector*prod3
}

var rv = Vector3D.new(0, -1, -1)
var rp = Vector3D.new(0,  0, 10)
var pn = Vector3D.new(0,  0,  1)
var pp = Vector3D.new(0,  0,  5)
var ip = intersectPoint.call(rv, rp, pn, pp)
System.print("The ray intersects the plane at %(ip).")


class Line { fcn init(pxyz, ray_xyz)   { var pt=pxyz, ray=ray_xyz;       } }
class Plane{ fcn init(pxyz, normal_xyz){ var pt=pxyz, normal=normal_xyz; } }

fcn dotP(a,b){ a.zipWith('*,b).sum(0.0); }  # dot product --> x
fcn linePlaneIntersection(line,plane){
   cos:=dotP(plane.normal,line.ray); # cosine between normal & ray
   _assert_((not cos.closeTo(0,1e-6)),
      "Vectors are orthogonol; no intersection or line within plane");
   w:=line.pt.zipWith('-,plane.pt); # difference between P0 and V0
   si:=-dotP(plane.normal,w)/cos;   # line segment where it intersets the plane
      # point where line intersects the plane:
   //w.zipWith('+,line.ray.apply('*,si)).zipWith('+,plane.pt);  // or
   w.zipWith('wrap(w,r,pt){ w + r*si + pt },line.ray,plane.pt);
}


*        Find the missing permutation - 19/10/2015
PERMMISX CSECT
         USING  PERMMISX,R15       set base register
         LA     R4,0               i=0
         LA     R6,1               step
         LA     R7,23              to
LOOPI    BXH    R4,R6,ELOOPI       do i=1 to hbound(perms)
         LA     R5,0               j=0
         LA     R8,1               step
         LA     R9,4               to
LOOPJ    BXH    R5,R8,ELOOPJ       do j=1 to hbound(miss)
         LR     R1,R4              i
         SLA    R1,2               *4
         LA     R3,PERMS-5(R1)     @perms(i)
         AR     R3,R5              j
         LA     R2,MISS-1(R5)      @miss(j)
         XC     0(1,R2),0(R3)      miss(j)=miss(j) xor substr(perms(i),j,1)
         B      LOOPJ
ELOOPJ   B      LOOPI
ELOOPI   XPRNT  MISS,15            print buffer
         XR     R15,R15            set return code
         BR     R14                return to caller
PERMS    DC     C'ABCD',C'CABD',C'ACDB',C'DACB',C'BCDA',C'ACBD'
         DC     C'ADCB',C'CDAB',C'DABC',C'BCAD',C'CADB',C'CDBA'
         DC     C'CBAD',C'ABDC',C'ADBC',C'BDCA',C'DCBA',C'BACD'
         DC     C'BADC',C'BDAC',C'CBDA',C'DBCA',C'DCAB'
MISS     DC     4XL1'00',C' is missing'  buffer
         YREGS
         END    PERMMISX


PRMLEN: equ     4               ; length of permutation string
puts:   equ     9               ; CP/M print string
        org     100h
        lxi     d,perms         ; Start with first permutation
perm:   lxi     h,mperm         ; Missing permutation
        mvi     b,PRMLEN        ; Length of permutation
char:   ldax    d               ; Load character
        ora     a               ; Done?
        jz      done
        xra     m               ; If not, XOR into missing permutation
        mov     m,a
        inx     h               ; Increment pointers
        inx     d
        dcr     b               ; Next character of current permutation
        jnz     char
        jmp     perm            ; Next permutation
done:   lxi     d,msg           ; Print the message and exit
        mvi     c,puts
        jmp     5
msg:    db      'Missing permutation: '
mperm:  db      0,0,0,0,'$'     ; placeholder
perms:  db      'ABCD','CABD','ACDB','DACB','BCDA','ACBD','ADCB','CDAB'
        db      'DABC','BCAD','CADB','CDBA','CBAD','ABDC','ADBC','BDCA'
        db      'DCBA','BACD','BADC','BDAC','CBDA','DBCA','DCAB'
        db      0               ; end marker


program FizzBuzz;

{$APPTYPE CONSOLE}

uses SysUtils;

var
  i: Integer;
begin
  for i := 1 to 100 do
  begin
    if i mod 15 = 0 then
      Writeln('FizzBuzz')
    else if i mod 3 = 0 then
      Writeln('Fizz')
    else if i mod 5 = 0 then
      Writeln('Buzz')
    else
      Writeln(i);
  end;
end.


preYear = 1900
for yyyy      = 1900 to 2100
   for mm     = 1 to 12                ' go thru all 12 months
      dayOne$ = mm;"-01-";yyyy         ' First day of month
      n       = date$(dayOne$)         ' Days since 1700
      dow     = 1 + (n mod 7)          ' Day of Week month begins
      m1      = mm                     '
      n1      = n + 27                 ' find end of month starting with 27th day
      while   m1 = mm                  ' if month changes we have the end of the month
         n1   = n1 + 1
         n$   = date$(n1)
         m1   = val(left$(n$,2))
      wend
      mmDays  = n1 - n                 ' Days in the Month
      if dow  = 4 and mmDays = 31 then ' test for 5 weeks
         count = count + 1
         print using("###",count);" ";yyyy;"-";left$("0";mm,2)
      end if

   next mm
   if preCount = count then
     noCount = noCount + 1             ' count years that have none
     print yyyy;" has none ";noCount
   end if
   preCount = count
next yyyy


extern crate chrono;
use chrono::prelude::*;

/// Months with 31 days
const LONGMONTHS: [u32; 7] = [1, 3, 5, 7, 8, 10, 12];

/// Get all the tuples (year, month) in wich there is five Fridays, five Saturdays and five Sundays
/// between the years start and end (inclusive).
fn five_weekends(start: i32, end: i32) -> Vec<(i32, u32)> {
    let mut out = vec![];

    for year in start..=end {
        for month in LONGMONTHS.iter() {
            // Five weekends if a 31-days month starts with a Friday.
            if Local.ymd(year, *month, 1).weekday() == Weekday::Fri {
                out.push((year, *month));
            }
        }
    }

    out
}

fn main() {
    let out = five_weekends(1900, 2100);

    let len = out.len();
    println!(
        "There are {} months of which the first and last five are:",
        len
    );
    for (y, m) in &out[..5] {
        println!("\t{} / {}", y, m);
    }
    println!("...");
    for (y, m) in &out[(len - 5..)] {
        println!("\t{} / {}", y, m);
    }
}

#[test]
fn test() {
    let out = five_weekends(1900, 2100);
    assert_eq!(out.len(), 201);
}


import java.util.Calendar._
import java.util.GregorianCalendar

import org.scalatest.{FlatSpec, Matchers}

class FiveWeekends extends FlatSpec with Matchers {

  case class YearMonth[T](year: T, month: T)
  implicit class CartesianProd[T](val seq: Seq[T]) {
    def x(other: Seq[T]) = for(s1 <- seq; s2 <- other) yield YearMonth(year=s1,month=s2)
    def -(other: Seq[T]): Seq[T] = seq diff other
  }

  def has5weekends(ym: { val year: Int; val month: Int}) = {
    val date = new GregorianCalendar(ym.year, ym.month-1, 1)
    date.get(DAY_OF_WEEK) == FRIDAY && date.getActualMaximum(DAY_OF_MONTH) == 31
  }

  val expectedFirstFive = Seq(
    YearMonth(1901,3), YearMonth(1902,8), YearMonth(1903,5), YearMonth(1904,1), YearMonth(1904,7))
  val expectedFinalFive = Seq(
    YearMonth(2097,3), YearMonth(2098,8), YearMonth(2099,5), YearMonth(2100,1), YearMonth(2100,10))
  val expectedNon5erYears = Seq(1900, 1906, 1917, 1923, 1928, 1934, 1945, 1951, 1956, 1962,
                                1973, 1979, 1984, 1990, 2001, 2007, 2012, 2018, 2029, 2035,
                                2040, 2046, 2057, 2063, 2068, 2074, 2085, 2091, 2096)

  "Five Weekend Algorithm" should "match specification" in {
    val months = (1900 to 2100) x (1 to 12) filter has5weekends
    months.size shouldBe 201
    months.take(5) shouldBe expectedFirstFive
    months.takeRight(5) shouldBe expectedFinalFive

    (1900 to 2100) - months.map(_.year) shouldBe expectedNon5erYears
  }
}


        cpu     8086
        org     100h
        mov     si,perms                ; Start of permutations
        xor     bx,bx                   ; First word of permutation
        xor     dx,dx                   ; Second word of permutation
        mov     cx,23                   ; There are 23 permutations given
perm:   lodsw                           ; Load first word of permutation
        xor     bx,ax                   ; XOR with first word of missing
        lodsw                           ; Load second word of permutation
        xor     dx,ax                   ; XOR with second word of missing
        loop    perm                    ; Get next permutation
        mov     [mperm],bx              ; Store in placeholder
        mov     [mperm+2],dx
        mov     ah,9                    ; Write output
        mov     dx,msg
        int     21h
        ret
msg:    db      'Missing permutation: '
mperm:  db      0,0,0,0,'$'             ; Placeholder
perms:  db      'ABCD','CABD','ACDB','DACB','BCDA','ACBD','ADCB','CDAB'
        db      'DABC','BCAD','CADB','CDBA','CBAD','ABDC','ADBC','BDCA'
        db      'DCBA','BACD','BADC','BDAC','CBDA','DBCA','DCAB'


PROC Main()
  DEFINE PTR="CARD"
  DEFINE COUNT="23"
  PTR ARRAY perm(COUNT)
  CHAR ARRAY s,missing=[4 0 0 0 0]
  BYTE i,j

  perm(0)="ABCD"  perm(1)="CABD"
  perm(2)="ACDB"  perm(3)="DACB"
  perm(4)="BCDA"  perm(5)="ACBD"
  perm(6)="ADCB"  perm(7)="CDAB"
  perm(8)="DABC"  perm(9)="BCAD"
  perm(10)="CADB" perm(11)="CDBA"
  perm(12)="CBAD" perm(13)="ABDC"
  perm(14)="ADBC" perm(15)="BDCA"
  perm(16)="DCBA" perm(17)="BACD"
  perm(18)="BADC" perm(19)="BDAC"
  perm(20)="CBDA" perm(21)="DBCA"
  perm(22)="DCAB"

  FOR i=0 TO COUNT-1
  DO
    s=perm(i)
    FOR j=1 TO 4
    DO
      missing(j)==XOR s(j)
    OD
  OD

  Print(missing)
RETURN


each { x range(1 100)
    ?  { divisible(x 3)
        p:'Fizz' }
    ?  { divisible(x 5)
        p:'Buzz' }
    -? { !:divisible(x 3)
        p:x }
    o
}


$ include "seed7_05.s7i";
  include "time.s7i";

const proc: main is func
  local
    var integer: months is 0;
    var time: firstDayInMonth is time.value;
  begin
    for firstDayInMonth.year range 1900 to 2100 do
      for firstDayInMonth.month range 1 to 12 do
        if daysInMonth(firstDayInMonth) = 31 and dayOfWeek(firstDayInMonth) = 5 then
          writeln(firstDayInMonth.year <& "-" <& firstDayInMonth.month lpad0 2);
          incr(months);
        end if;
      end for;
    end for;
    writeln("Number of months:" <& months);
  end func;


require('DateTime');

var happymonths = [];
var workhardyears = [];
var longmonths = [1, 3, 5, 7, 8, 10, 12];

range(1900, 2100).each { |year|
   var countmonths = 0;
   longmonths.each { |month|
        var dt = %s'DateTime'.new(
            year => year,
            month => month,
            day   => 1
        );

        if (dt.day_of_week == 5) {
            countmonths++;
            var yearfound = dt.year;
            var monthfound = dt.month_name;
            happymonths.append(join("  ", yearfound, monthfound));
      }
   }

    if (countmonths == 0) {
        workhardyears.append(year);
    }
}

say "There are #{happymonths.len} months with 5 full weekends!";
say "The first 5 and the last 5 of them are:";
say happymonths.first(5).join("\n");
say happymonths.last(5).join("\n");
say "No long weekends in the following #{workhardyears.len} years:";
say workhardyears.join(",");


with Ada.Text_IO;
procedure Missing_Permutations is
   subtype Permutation_Character is Character range 'A' .. 'D';

   Character_Count : constant :=
      1 + Permutation_Character'Pos (Permutation_Character'Last)
        - Permutation_Character'Pos (Permutation_Character'First);

   type Permutation_String is
     array (1 .. Character_Count) of Permutation_Character;

   procedure Put (Item : Permutation_String) is
   begin
      for I in Item'Range loop
         Ada.Text_IO.Put (Item (I));
      end loop;
   end Put;

   Given_Permutations : array (Positive range <>) of Permutation_String :=
     ("ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD",
      "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA",
      "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD",
      "BADC", "BDAC", "CBDA", "DBCA", "DCAB");

   Count     : array (Permutation_Character, 1 .. Character_Count) of Natural
      := (others => (others => 0));
   Max_Count : Positive := 1;

   Missing_Permutation : Permutation_String;
begin
   for I in Given_Permutations'Range loop
      for Pos in 1 .. Character_Count loop
         Count (Given_Permutations (I) (Pos), Pos)   :=
           Count (Given_Permutations (I) (Pos), Pos) + 1;
         if Count (Given_Permutations (I) (Pos), Pos) > Max_Count then
            Max_Count := Count (Given_Permutations (I) (Pos), Pos);
         end if;
      end loop;
   end loop;

   for Char in Permutation_Character loop
      for Pos in 1 .. Character_Count loop
         if Count (Char, Pos) < Max_Count then
            Missing_Permutation (Pos) := Char;
         end if;
      end loop;
   end loop;

   Ada.Text_IO.Put_Line ("Missing Permutation:");
   Put (Missing_Permutation);
end Missing_Permutations;


proc nonrec main() void:
    byte i;
    for i from 1 upto 100 do
        if i % 15 = 0 then writeln("FizzBuzz")
        elif i % 5 = 0 then writeln("Buzz")
        elif i % 3 = 0 then writeln("Fizz")
        else writeln(i)
        fi
    od
corp


! TRANSLATION OF FREEBASIC VERSION ;
BEGIN

    INTEGER PROCEDURE WD(M, D, Y); INTEGER M, D, Y;
    BEGIN
        ! ZELLERISH
        ! 0 = SUNDAY, 1 = MONDAY, 2 = TUESDAY, 3 = WEDNESDAY
        ! 4 = THURSDAY, 5 = FRIDAY, 6 = SATURDAY
        ;

        IF M < 3 THEN        ! IF M = 1 OR M = 2 THEN ;
        BEGIN
            M := M + 12;
            Y := Y - 1
        END;
        WD := MOD(Y + (Y // 4)
                    - (Y // 100)
                    + (Y // 400)
                    + D + ((153 * M + 8) // 5), 7)
    END WD;

    ! ------=< MAIN >=------
    ! ONLY MONTHS WITH 31 DAY CAN HAVE FIVE WEEKENDS
    ! THESE MONTHS ARE: JANUARY, MARCH, MAY, JULY, AUGUST, OCTOBER, DECEMBER
    ! IN NR: 1, 3, 5, 7, 8, 10, 12
    ! THE 1E DAY NEEDS TO BE ON A FRIDAY (= 5)
    ;

    TEXT PROCEDURE MONTHNAMES(M); INTEGER M;
        MONTHNAMES :- IF M =  1 THEN "JANUARY"
                 ELSE IF M =  2 THEN "FEBRUARY"
                 ELSE IF M =  3 THEN "MARCH"
                 ELSE IF M =  4 THEN "APRIL"
                 ELSE IF M =  5 THEN "MAY"
                 ELSE IF M =  6 THEN "JUNE"
                 ELSE IF M =  7 THEN "JULY"
                 ELSE IF M =  8 THEN "AUGUST"
                 ELSE IF M =  9 THEN "SEPTEMBER"
                 ELSE IF M = 10 THEN "OCTOBER"
                 ELSE IF M = 11 THEN "NOVEMBER"
                 ELSE IF M = 12 THEN "DECEMBER"
                 ELSE NOTEXT;

    INTEGER M, YR, TOTAL, I, J;
    INTEGER ARRAY YR_WITHOUT(1:200);
    TEXT ANSWER;

    FOR YR := 1900 STEP 1 UNTIL 2100 DO  ! GREGORIAN CALENDAR ;
    BEGIN
        ANSWER :- NOTEXT;
        FOR M := 1 STEP 2 UNTIL 12 DO
        BEGIN
            IF M = 9 THEN M := 8;
            IF WD(M, 1, YR) = 5 THEN
            BEGIN
                ANSWER :- ANSWER & MONTHNAMES(M) & ", ";
                TOTAL := TOTAL + 1
            END
        END;
        IF ANSWER =/= NOTEXT THEN
        BEGIN
            OUTIMAGE;
            OUTINT(YR, 4); OUTTEXT(" | ");
            OUTTEXT(ANSWER.SUB(1, ANSWER.LENGTH - 2)) ! GET RID OF EXTRA " ," ;
        END
        ELSE
        BEGIN
            I := I + 1;
            YR_WITHOUT(I) := YR
        END
    END;

    OUTIMAGE;
    OUTTEXT("NR OF MONTH FOR 1900 TO 2100 THAT HAS FIVE WEEKENDS ");
    OUTINT(TOTAL, 0);
    OUTIMAGE;
    OUTIMAGE;
    OUTINT(I, 0);
    OUTTEXT(" YEARS DON'T HAVE MONTHS WITH FIVE WEEKENDS");
    OUTIMAGE;

    FOR J := 1 STEP 1 UNTIL I DO
    BEGIN
        OUTINT(YR_WITHOUT(J), 0); OUTCHAR(' ');
        IF MOD(J, 8) = 0 THEN OUTIMAGE
    END;
    OUTIMAGE

END.


package require Tcl 8.5

set months {}
set years {}
for {set year 1900} {$year <= 2100} {incr year} {
    set count [llength $months]
    foreach month {Jan Mar May Jul Aug Oct Dec} {
	set date [clock scan "$month/01/$year" -format "%b/%d/%Y" -locale en_US]
	if {[clock format $date -format %u] == 5} {
	    # Month with 31 days that starts on a Friday => has 5 weekends
	    lappend months "$month $year"
	}
    }
    if {$count == [llength $months]} {
	# No change to number of months; year must've been without
	lappend years $year
    }
}
puts "There are [llength $months] months with five weekends"
puts [join [list {*}[lrange $months 0 4] ... {*}[lrange $months end-4 end]] \n]
puts "There are [llength $years] years without any five-weekend months"
puts [join $years ","]


void
paste(record r, index x, text p, integer a)
{
    p = insert(p, -1, a);
    x.delete(a);
    if (~x) {
        x.vcall(paste, -1, r, x, p);
    } else {
        r[p] = 0;
    }
    x[a] = 0;
}

integer
main(void)
{
    record r;
    list l;
    index x;

    l.bill(0, "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB",
           "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC",
           "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB");

    x['A'] = x['B'] = x['C'] = x['D'] = 0;

    x.vcall(paste, -1, r, x, "");

    l.ucall(r_delete, 1, r);

    o_(r.low, "\n");

    return 0;
}


BEGIN # find the missing permutation in a list using the XOR method of the Raku sample #
    # the list to find the missing permutation of #
    []STRING list = ( "ABCD", "CABD", "ACDB", "DACB", "BCDA"
                    , "ACBD", "ADCB", "CDAB", "DABC", "BCAD"
                    , "CADB", "CDBA", "CBAD", "ABDC", "ADBC"
                    , "BDCA", "DCBA", "BACD", "BADC", "BDAC"
                    , "CBDA", "DBCA", "DCAB"
                    );
    # sets b to b XOR v and returns b #
    PRIO XORAB = 1;
    OP   XORAB = ( REF BITS b, BITS v )REF BITS: b := b XOR v;

    # loop through each character of each element of the list #
    FOR c pos FROM LWB list[ LWB list ] TO UPB list[ LWB list ] DO
        # loop through each element of the list #
        BITS m := 16r0;
        FOR l pos FROM LWB list TO UPB list DO
            m XORAB BIN ABS list[ l pos ][ c pos ]
        OD;
        print( ( REPR ABS m ) )
    OD
END


$$ MODE TUSCRIPT
LOOP year=1900,2100
 LOOP month="1'3'5'7'8'10'12"
 SET dayofweek=DATE (number,1,month,year,nummer)
 IF (dayofweek==5) PRINT year,"-",month
 ENDLOOP
ENDLOOP


' ------=< MAIN >=------
' only months with 31 day can have five weekends
' these months are: January, March, May, July, August, October, December
' in nr: 1, 3, 5, 7, 8, 10, 12
' the 1e day needs to be on a friday (= 5)

For y = 1900 To 2100  ' Gregorian calendar
    a = 0
    For m = 1 To 12 Step 2
        If m = 9 Then m = 8
        If Func(_wd(m , 1 , y)) = 5 Then
           If a Then
              Print ", ";
           Else
              Print y; " | ";
              a = 1
           EndIf
           GoSub m*10
           t = t + 1
        EndIf
    Next
    If a Then
       Print
    Else
       i = i + 1
       @(i) = y
    EndIf
Next

Print
Print "Number of months from 1900 to 2100 that have five weekends: ";t
Print
Print i;" years don't have months with five weekends:"
Print

For j = 1 To i
    Print @(j); " ";
    If (j % 8) = 0 Then Print
Next

Print
End

_wd Param(3)
    ' Zellerish
    ' 0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday
    ' 4 = Thursday, 5 = Friday, 6 = Saturday

    If [email protected] < 3 Then        ' If [email protected] = 1 Or [email protected] = 2 Then
        [email protected] = [email protected] + 12
        [email protected] = [email protected] - 1
    EndIf
Return (([email protected] + ([email protected] / 4) - ([email protected] / 100) + ([email protected] / 400) + [email protected] + ((153 * [email protected] + 8) / 5)) % 7)

 10 Print "January"; : Return
 20 Print "February"; : Return
 30 Print "March"; : Return
 40 Print "April"; : Return
 50 Print "May"; : Return
 60 Print "June"; : Return
 70 Print "July"; : Return
 80 Print "August"; : Return
 90 Print "September"; : Return
100 Print "October"; : Return
110 Print "November"; : Return
120 Print "December"; : Return


echo "Creating cal-file..."
echo > cal.txt
for ((y=1900; y <= 2100; y++)); do
  for ((m=1; m <= 12; m++)); do
   #echo $m $y
    cal -m $m $y >> cal.txt
  done
done
ls -la cal.txt

echo "Looking for month with 5 weekends:"
awk -f 5weekends.awk  cal.txt


missing ← ((⊂↓⍳¨⌊/) +⌿∘(⊢∘.=∪∘∊)) ⌷ ∪∘∊


use framework "Foundation" -- ( sort )

--------------- RAREST LETTER IN EACH COLUMN -------------
on run
    concat(map(composeList({¬
        head, ¬
        minimumBy(comparing(|length|)), ¬
        group, ¬
        sort}), ¬
        transpose(map(chars, ¬
            |words|("ABCD CABD ACDB DACB BCDA ACBD " & ¬
                "ADCB CDAB DABC BCAD CADB CDBA " & ¬
                "CBAD ABDC ADBC BDCA DCBA BACD " & ¬
                "BADC BDAC CBDA DBCA DCAB")))))

    --> "DBAC"
end run

-------------------- GENERIC FUNCTIONS -------------------

-- chars :: String -> [String]
on chars(s)
    characters of s
end chars

-- Ordering  :: (-1 | 0 | 1)
-- compare :: a -> a -> Ordering
on compare(a, b)
    if a < b then
        -1
    else if a > b then
        1
    else
        0
    end if
end compare

-- comparing :: (a -> b) -> (a -> a -> Ordering)
on comparing(f)
    script
        on |λ|(a, b)
            tell mReturn(f) to compare(|λ|(a), |λ|(b))
        end |λ|
    end script
end comparing

-- composeList :: [(a -> a)] -> (a -> a)
on composeList(fs)
    script
        on |λ|(x)
            script go
                on |λ|(f, a)
                    mReturn(f)'s |λ|(a)
                end |λ|
            end script
            foldr(go, x, fs)
        end |λ|
    end script
end composeList

-- concat :: [[a]] -> [a]
-- concat :: [String] -> String
on concat(xs)
    set lng to length of xs
    if 0 < lng and string is class of (item 1 of xs) then
        set acc to ""
    else
        set acc to {}
    end if
    repeat with i from 1 to lng
        set acc to acc & item i of xs
    end repeat
    acc
end concat

-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        repeat with i from 1 to lng
            set v to |λ|(v, item i of xs, i, xs)
        end repeat
        return v
    end tell
end foldl

-- foldr :: (b -> a -> a) -> a -> [b] -> a
on foldr(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        repeat with i from lng to 1 by -1
            set v to |λ|(item i of xs, v, i, xs)
        end repeat
        return v
    end tell
end foldr

-- group :: Eq a => [a] -> [[a]]
on group(xs)
    script eq
        on |λ|(a, b)
            a = b
        end |λ|
    end script

    groupBy(eq, xs)
end group

-- groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
on groupBy(f, xs)
    set mf to mReturn(f)

    script enGroup
        on |λ|(a, x)
            if length of (active of a) > 0 then
                set h to item 1 of active of a
            else
                set h to missing value
            end if

            if h is not missing value and mf's |λ|(h, x) then
                {active:(active of a) & x, sofar:sofar of a}
            else
                {active:{x}, sofar:(sofar of a) & {active of a}}
            end if
        end |λ|
    end script

    if length of xs > 0 then
        set dct to foldl(enGroup, {active:{item 1 of xs}, sofar:{}}, tail(xs))
        if length of (active of dct) > 0 then
            sofar of dct & {active of dct}
        else
            sofar of dct
        end if
    else
        {}
    end if
end groupBy

-- head :: [a] -> a
on head(xs)
    if length of xs > 0 then
        item 1 of xs
    else
        missing value
    end if
end head

-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
    set {dlm, my text item delimiters} to {my text item delimiters, strText}
    set strJoined to lstText as text
    set my text item delimiters to dlm
    return strJoined
end intercalate

-- length :: [a] -> Int
on |length|(xs)
    length of xs
end |length|

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- minimumBy :: (a -> a -> Ordering) -> [a] -> a
on minimumBy(f)
    script
        on |λ|(xs)
            if length of xs < 1 then return missing value
            tell mReturn(f)
                set v to item 1 of xs
                repeat with x in xs
                    if |λ|(x, v) < 0 then set v to x
                end repeat
                return v
            end tell
        end |λ|
    end script
end minimumBy

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn

-- sort :: [a] -> [a]
on sort(xs)
    ((current application's NSArray's arrayWithArray:xs)'s ¬
        sortedArrayUsingSelector:"compare:") as list
end sort

-- tail :: [a] -> [a]
on tail(xs)
    if length of xs > 1 then
        items 2 thru -1 of xs
    else
        {}
    end if
end tail

-- transpose :: [[a]] -> [[a]]
on transpose(xss)
    script column
        on |λ|(_, iCol)
            script row
                on |λ|(xs)
                    item iCol of xs
                end |λ|
            end script

            map(row, xss)
        end |λ|
    end script

    map(column, item 1 of xss)
end transpose

-- words :: String -> [String]
on |words|(s)
    words of s
end |words|


var i : Integer;

for i := 1 to 100 do begin
   if i mod 15 = 0 then
      PrintLn('FizzBuzz')
   else if i mod 3 = 0 then
      PrintLn('Fizz')
   else if i mod 5 = 0 then
      PrintLn('Buzz')
   else PrintLn(i);
end;


Option Explicit

Sub Main()
Dim y As Long, m As Long, t As String, cpt As Long, cptm As Long
    For y = 1900 To 2100
        t = vbNullString
        For m = 1 To 12 Step 2
            If m = 9 Then m = 8
            If Weekday(DateSerial(y, m, 1)) = vbFriday Then
                t = t & ", " & m
                cptm = cptm + 1
            End If
        Next
        If t <> "" Then
            Debug.Print y & t
        Else
            cpt = cpt + 1
        End If
    Next
    Debug.Print "There is " & cptm & " months with five full weekends from the year 1900 through 2100"
    Debug.Print "There is " & cpt & " years which don't have months with five weekends"
End Sub


For y = 1900 To 2100
	For m = 1 To 12
		d = DateSerial(y, m + 1, 1) - 1
		If Day(d) = 31 And Weekday(d) = vbSunday Then
			WScript.Echo y & ", " & MonthName(m)
			i = i + 1
		End If
	Next
Next

WScript.Echo vbCrLf & "Total = " & i & " months"


perms: [
    "ABCD" "CABD" "ACDB" "DACB" "BCDA" "ACBD" "ADCB" "CDAB" "DABC"
    "BCAD" "CADB" "CDBA" "CBAD" "ABDC" "ADBC" "BDCA" "DCBA" "BACD"
    "BADC" "BDAC" "CBDA" "DBCA" "DCAB"
]

allPerms: map permutate split "ABCD" => join

print first difference allPerms perms


IncompleteList := "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB"

CompleteList := Perm( "ABCD" )
Missing := ""

Loop, Parse, CompleteList, `n, `r
  If !InStr( IncompleteList , A_LoopField )
    Missing .= "`n" A_LoopField

MsgBox Missing Permutation(s):%Missing%

;-------------------------------------------------

; Shortened version of [VxE]'s permutation function
; http://www.autohotkey.com/forum/post-322251.html#322251
Perm( s , dL="" , t="" , p="") {
   StringSplit, m, s, % d := SubStr(dL,1,1) , %t%
   IfEqual, m0, 1, return m1 d p
   Loop %m0%
   {
      r := m1
      Loop % m0-2
         x := A_Index + 1, r .= d m%x%
      L .= Perm(r, d, t, m%m0% d p)"`n" , mx := m1
      Loop % m0-1
         x := A_Index + 1, m%A_Index% := m%x%
      m%m0% := mx
   }
   return substr(L, 1, -1)
}


var n = 1

while n < 20 {
    if n % 15 == 0 {
        print("fizzbuzz")
    } else if n % 3 == 0 {
        print("fizz")
    } else if n % 5 == 0 {
        print("buzz")
    } else {
        print(n)
    }

    n = n + 1
}


import "/date" for Date
import "/seq" for Lst

var dates = []
var years = []
for (y in 1900..2100) {
    var hasFive = false
    for (m in 1..12) {
        var fri = 0
        var sat = 0
        var sun = 0
        for (d in 1..Date.monthLength(y, m)) {
            var d = Date.new(y, m, d)
            var dow = d.dayOfWeek
            if (dow == 5) {
                fri = fri + 1
            } else if (dow == 6) {
                sat = sat + 1
            } else if (dow == 7) {
                sun = sun + 1
            }
        }
        var fd = Date.new(y, m, 1)
        if (fri == 5 && sat == 5 && sun == 5) {
            dates.add(fd)
            hasFive = true
        }
    }
    if (!hasFive) years.add(y)
}

Date.default = "mmm|-|yyyy"
System.print("Between 1900 and 2100:-")
System.print("  There are %(dates.count) months that have five full weekends.")
System.print("  The first 5 are:")
for (i in 0..4) System.print("    %(dates[i])")
System.print("  and the last 5 are:")
for (i in -5..-1) System.print("    %(dates[i])")
System.print("\n  There are %(years.count) years that do not have at least one five-weekend month, namely:")
var chunks = Lst.chunks(years, 10)
for (i in 0...chunks.count) System.print("    %(chunks[i])")


      DIM perms$(22), miss&(4)
      perms$() = "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", \
      \  "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", \
      \  "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"

      FOR i% = 0 TO DIM(perms$(),1)
        FOR j% = 1 TO DIM(miss&(),1)
          miss&(j%-1) EOR= ASCMID$(perms$(i%),j%)
        NEXT
      NEXT
      PRINT $$^miss&(0) " is missing"
      END


for i range 1 100:
	if = 0 % i 15:
		"FizzBuzz"
	elseif = 0 % i 3:
		"Fizz"
	elseif = 0 % i 5:
		"Buzz"
	else:
		i
	!print


include c:\cxpl\codes;                  \intrinsic 'code' declarations

func    WeekDay(Year, Month, Day);      \Return day of week (0=Sat 1=Sun..6=Fri)
int     Year, Month, Day;
[if Month<=2 then [Month:= Month+12;  Year:= Year-1];
return rem((Day + (Month+1)*26/10 + Year + Year/4 + Year/100*6 + Year/400) / 7);
];      \WeekDay

int     MonthTbl, Year, I, C;
[MonthTbl:= [1, 3, 5, 7, 8, 10, 12];            \months with 31 days
C:= 0;
for Year:= 1900 to 2100 do
  for I:= 0 to 6 do                             \for all the 31-day months...
    if WeekDay(Year, MonthTbl(I), 1) = 6 then   \first of month is a Friday
        [C:= C+1;                               \count this year
        if C<=5 or C>201-5 then                 \show first 5 and last 5 years
                [IntOut(0, Year);  ChOut(0, ^ );
                 IntOut(0, MonthTbl(I));  CrLf(0);
                ];
        ];
IntOut(0, C);  CrLf(0);                         \show number of years

\Count and show all years that don't have any 5-weekend months
C:= 0;
for Year:= 1900 to 2100 do
        [for I:= 0 to 6 do                      \for all the 31-day months...
            if WeekDay(Year, MonthTbl(I), 1) = 6 \Friday\ then
                I:= 10;                         \bail out of 'for' loop
        if I<10 then                            \'for' loop completed
                [if (C&$F) = 0 then CrLf(0);    \(format 16 years per line)
                C:= C+1;                        \ without finding a 5-weekend
                IntOut(0, Year);  ChOut(0, ^ ); \ so show the year
                ];
        ];
CrLf(0);  IntOut(0, C);  CrLf(0);               \show number of years
]


var [const] D=Time.Date, r=L();
foreach y,m in ([1900..2100],[1..12]){
   if (D.daysInMonth(y,m)==31 and 5==D.weekDay(y,m,1)) r.append(String(y,"-",m))
}


#include <stdio.h>

#define N 4
const char *perms[] = {
	"ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB",
	"DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA",
	"DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB",
};

int main()
{
	int i, j, n, cnt[N];
	char miss[N];

	for (n = i = 1; i < N; i++) n *= i; /* n = (N-1)!, # of occurrence */

	for (i = 0; i < N; i++) {
		for (j = 0; j < N; j++) cnt[j] = 0;

		/* count how many times each letter occur at position i */
		for (j = 0; j < sizeof(perms)/sizeof(const char*); j++)
			cnt[perms[j][i] - 'A']++;

		/* letter not occurring (N-1)! times is the missing one */
		for (j = 0; j < N && cnt[j] == n; j++);

		miss[i] = j + 'A';
	}
	printf("Missing: %.*s\n", N, miss);

	return 0;

}


using System;
using System.Collections.Generic;

namespace MissingPermutation
{
    class Program
    {
        static void Main()
        {
            string[] given = new string[] { "ABCD", "CABD", "ACDB", "DACB",
                                            "BCDA", "ACBD", "ADCB", "CDAB",
                                            "DABC", "BCAD", "CADB", "CDBA",
                                            "CBAD", "ABDC", "ADBC", "BDCA",
                                            "DCBA", "BACD", "BADC", "BDAC",
                                            "CBDA", "DBCA", "DCAB" };

            List<string> result = new List<string>();
            permuteString(ref result, "", "ABCD");

            foreach (string a in result)
                if (Array.IndexOf(given, a) == -1)
                    Console.WriteLine(a + " is a missing Permutation");
        }

        public static void permuteString(ref List<string> result, string beginningString, string endingString)
        {
            if (endingString.Length <= 1)
            {
                result.Add(beginningString + endingString);
            }
            else
            {
                for (int i = 0; i < endingString.Length; i++)
                {
                    string newString = endingString.Substring(0, i) + endingString.Substring(i + 1);
                    permuteString(ref result, beginningString + (endingString.ToCharArray())[i], newString);
                }
            }
        }
    }
}


#include <algorithm>
#include <vector>
#include <set>
#include <iterator>
#include <iostream>
#include <string>

static const std::string GivenPermutations[] = {
  "ABCD","CABD","ACDB","DACB",
  "BCDA","ACBD","ADCB","CDAB",
  "DABC","BCAD","CADB","CDBA",
  "CBAD","ABDC","ADBC","BDCA",
  "DCBA","BACD","BADC","BDAC",
  "CBDA","DBCA","DCAB"
};
static const size_t NumGivenPermutations = sizeof(GivenPermutations) / sizeof(*GivenPermutations);

int main()
{
    std::vector<std::string> permutations;
    std::string initial = "ABCD";
    permutations.push_back(initial);

    while(true)
    {
        std::string p = permutations.back();
        std::next_permutation(p.begin(), p.end());
        if(p == permutations.front())
            break;
        permutations.push_back(p);
    }

    std::vector<std::string> missing;
    std::set<std::string> given_permutations(GivenPermutations, GivenPermutations + NumGivenPermutations);
    std::set_difference(permutations.begin(), permutations.end(), given_permutations.begin(),
        given_permutations.end(), std::back_inserter(missing));
    std::copy(missing.begin(), missing.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
    return 0;
}


for i = 1 to 100
  if i mod 15 = 0
    print "FizzBuzz"
  elif i mod 5 = 0
    print "Buzz"
  elif i mod 3 = 0
    print "Fizz"
  else
    print i
  .
.


(use 'clojure.math.combinatorics)
(use 'clojure.set)

(def given (apply hash-set (partition 4 5 "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB" )))
(def s1 (apply hash-set (permutations "ABCD")))
(def missing (difference s1 given))


missing_permutation = (arr) ->
  # Find the missing permutation in an array of N! - 1 permutations.

  # We won't validate every precondition, but we do have some basic
  # guards.
  if arr.length == 0
    throw Error "Need more data"
  if arr.length == 1
      return [arr[0][1] + arr[0][0]]

  # Now we know that for each position in the string, elements should appear
  # an even number of times (N-1 >= 2).  We can use a set to detect the element appearing
  # an odd number of times.  Detect odd occurrences by toggling admission/expulsion
  # to and from the set for each value encountered.  At the end of each pass one element
  # will remain in the set.
  result = ''
  for pos in [0...arr[0].length]
      set = {}
      for permutation in arr
          c = permutation[pos]
          if set[c]
            delete set[c]
          else
            set[c] = true
      for c of set
        result += c
        break
  result

given = '''ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
  CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB'''

arr = (s for s in given.replace('\n', ' ').split ' ' when s != '')

console.log missing_permutation(arr)


DataRec := RECORD
    STRING  s;
END;

DataRec MakeDataRec(UNSIGNED c) := TRANSFORM
    SELF.s := MAP
        (
            c % 15 = 0  =>  'FizzBuzz',
            c % 3 = 0   =>  'Fizz',
            c % 5 = 0   =>  'Buzz',
            (STRING)c
        );
END;

d := DATASET(100,MakeDataRec(COUNTER));

OUTPUT(d);


(defparameter *permutations*
  '("ABCD" "CABD" "ACDB" "DACB" "BCDA" "ACBD" "ADCB" "CDAB" "DABC" "BCAD" "CADB" "CDBA"
    "CBAD" "ABDC" "ADBC" "BDCA" "DCBA" "BACD" "BADC" "BDAC" "CBDA" "DBCA" "DCAB"))

(defun missing-perm (perms)
  (let* ((letters (loop for i across (car perms) collecting i))
	 (l (/ (1+ (length perms)) (length letters))))
    (labels ((enum (n) (loop for i below n collecting i))
	     (least-occurs (pos)
	       (let ((occurs (loop for i in perms collecting (aref i pos))))
		 (cdr (assoc (1- l) (mapcar #'(lambda (letter)
						(cons (count letter occurs) letter))
					    letters))))))
      (concatenate 'string (mapcar #'least-occurs (enum (length letters)))))))


void main() {
    import std.stdio, std.string, std.algorithm, std.range, std.conv;

    immutable perms = "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC
                       BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD
                       BADC BDAC CBDA DBCA DCAB".split;

    // Version 1: test all permutations.
    immutable permsSet = perms
                         .map!representation
                         .zip(true.repeat)
                         .assocArray;
    auto perm = perms[0].dup.representation;
    do {
        if (perm !in permsSet)
            writeln(perm.map!(c => char(c)));
    } while (perm.nextPermutation);

    // Version 2: xor all the ASCII values, the uneven one
    // gets flushed out. Based on Raku (via Go).
    enum len = 4;
    char[len] b = 0;
    foreach (immutable p; perms)
        b[] ^= p[];
    b.writeln;

    // Version 3: sum ASCII values.
    immutable rowSum = perms[0].sum;
    len
    .iota
    .map!(i => to!char(rowSum - perms.transversal(i).sum % rowSum))
    .writeln;

    // Version 4: a checksum, Java translation. maxCode will be 36.
    immutable maxCode = reduce!q{a * b}(len - 1, iota(3, len + 1));

    foreach (immutable i; 0 .. len) {
        immutable code = perms.map!(p => perms[0].countUntil(p[i])).sum;

        // Code will come up 3, 1, 0, 2 short of 36.
        perms[0][maxCode - code].write;
    }
}


#import <Foundation/Foundation.h>

int main()
  autoreleasepool

    for int i in 1 .. 100
      s := ''
      if i % 3 == 0
        s << 'Fizz'
      if i % 5 == 0
        s << 'Buzz'
      Log( '(%d) %@', i, s )

  return 0


;; use the obvious methos
(lib 'list) ; for (permutations) function

;; input
(define perms '
(ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB))

;; generate all permutations
(define all-perms (map list->string (permutations '(A B C D))))
   → all-perms

;; {set} substraction
(set-substract (make-set all-perms) (make-set perms))
  → { DBAC }


defmodule RC do
  def find_miss_perm(head, perms) do
    all_permutations(head) -- perms
  end

  defp all_permutations(string) do
    list = String.split(string, "", trim: true)
    Enum.map(permutations(list), fn x -> Enum.join(x) end)
  end

  defp permutations([]), do: [[]]
  defp permutations(list), do: (for x <- list, y <- permutations(list -- [x]), do: [x|y])
end

perms = ["ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA",
         "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"]

IO.inspect RC.find_miss_perm( hd(perms), perms )


import "prelude.eg"
import "io.ego"

using System
using IO

def fizzbuzz =
    [ 100 -> print "100\n"
    | N ->
        if and ((N%3) == 0) ((N%5) == 0) then
            let _ = print "fizz buzz, " in fizzbuzz (N+1)
        else if (N%3) == 0 then
            let _ = print "fizz, " in fizzbuzz (N+1)
        else if (N%5) == 0 then
            let _ = print "buzz, " in fizzbuzz (N+1)
        else
            let _ = print N ", " in fizzbuzz (N+1) ]

def main = fizzbuzz 1


-module( find_missing_permutation ).

-export( [difference/2, task/0] ).

difference( Permutate_this, Existing_permutations ) -> all_permutations( Permutate_this ) -- Existing_permutations.

task() -> difference( "ABCD", existing_permutations() ).

all_permutations( String ) -> [[A, B, C, D] || A <- String, B <- String, C <- String, D <- String, is_different([A, B, C, D])].

existing_permutations() -> ["ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"].

is_different( [_H] ) -> true;
is_different( [H | T] ) -> not lists:member(H, T) andalso is_different( T ).


PROGRAM MISSING

CONST N=4

DIM PERMS$[23]

BEGIN
  PRINT(CHR$(12);) ! CLS
  DATA("ABCD","CABD","ACDB","DACB","BCDA","ACBD","ADCB")
  DATA("CDAB","DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC")
  DATA("BDCA","DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB")

  FOR I%=1 TO UBOUND(PERMS$,1) DO
    READ(PERMS$[I%])
  END FOR

  SOL$="...."

  FOR I%=1 TO N DO
    CH$=CHR$(I%+64)
    COUNT%=0
    FOR Z%=1 TO N DO
       COUNT%=0
       FOR J%=1 TO UBOUND(PERMS$,1) DO
          IF CH$=MID$(PERMS$[J%],Z%,1) THEN COUNT%=COUNT%+1 END IF
       END FOR
       IF COUNT%<>6 THEN
           !$RCODE="MID$(SOL$,Z%,1)=CH$"
       END IF
    END FOR
  END FOR
  PRINT("Solution is: ";SOL$)
END PROGRAM


class
	APPLICATION

create
	make

feature

	make
		do
			fizzbuzz
		end

	fizzbuzz
	        --Numbers up to 100, prints "Fizz" instead of multiples of 3, and "Buzz" for multiples of 5.
	        --For multiples of both 3 and 5 prints "FizzBuzz".
		do
			across
				1 |..| 100 as c
			loop
				if c.item \\ 15 = 0 then
					io.put_string ("FIZZBUZZ%N")
				elseif c.item \\ 3 = 0 then
					io.put_string ("FIZZ%N")
				elseif c.item \\ 5 = 0 then
					io.put_string ("BUZZ%N")
				else
					io.put_string (c.item.out + "%N")
				end
			end
		end

end


USING: io math.combinatorics sequences sets ;

"ABCD" all-permutations lines diff first print


 hex
 ABCD     CABD xor ACDB xor DACB xor BCDA xor ACBD xor
 ADCB xor CDAB xor DABC xor BCAD xor CADB xor CDBA xor
 CBAD xor ABDC xor ADBC xor BDCA xor DCBA xor BACD xor
 BADC xor BDAC xor CBDA xor DBCA xor DCAB xor
 cr .( Missing permutation: ) u.
 decimal


program missing_permutation

  implicit none
  character (4), dimension (23), parameter :: list =                    &
    & (/'ABCD', 'CABD', 'ACDB', 'DACB', 'BCDA', 'ACBD', 'ADCB', 'CDAB', &
    &   'DABC', 'BCAD', 'CADB', 'CDBA', 'CBAD', 'ABDC', 'ADBC', 'BDCA', &
    &   'DCBA', 'BACD', 'BADC', 'BDAC', 'CBDA', 'DBCA', 'DCAB'/)
  integer :: i, j, k

  do i = 1, 4
    j = minloc ((/(count (list (:) (i : i) == list (1) (k : k)), k = 1, 4)/), 1)
    write (*, '(a)', advance = 'no') list (1) (j : j)
  end do
  write (*, *)

end program missing_permutation


open list

prt x | x % 15 == 0 = "FizzBuzz"
      | x % 3 == 0  = "Fizz"
      | x % 5 == 0  = "Buzz"
      | else        = x

[1..100] |> map prt


' version 30-03-2017
' compile with: fbc -s console

Data "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD"
Data "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA"
Data "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD"
Data "BADC", "BDAC", "CBDA", "DBCA", "DCAB"

' ------=< MAIN >=------

Dim As ulong total(3, Asc("A") To Asc("D"))  ' total(0 to 3, 65 to 68)
Dim As ULong i, j, n = 24 \ 4   ' n! \ n
Dim As String tmp

For i = 1 To 23
    Read tmp
    For j = 0 To 3
        total(j, tmp[j]) += 1
    Next
Next

tmp = Space(4)
For i = 0 To 3
    For j = Asc("A") To Asc("D")
        If total(i, j) <> n Then
         tmp[i] = j
        End If
    Next
Next

Print "The missing permutation is : "; tmp

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


# our deficient list
L :=
[ "ABCD", "CABD", "ACDB", "DACB", "BCDA",
  "ACBD", "ADCB", "CDAB", "DABC", "BCAD",
  "CADB", "CDBA", "CBAD", "ABDC", "ADBC",
  "BDCA", "DCBA", "BACD", "BADC", "BDAC",
  "CBDA", "DBCA", "DCAB" ];

# convert L to permutations on 1..4
u := List(L, s -> List([1..4], i -> Position("ABCD", s[i])));

# set difference (with all permutations)
v := Difference(PermutationsList([1..4]), u);

# convert back to letters
s := "ABCD";
List(v, p -> List(p, i -> s[i]));


Enum.each 1..100, fn x ->
  IO.puts(case { rem(x,3) == 0, rem(x,5) == 0 } do
    { true, true }   -> "FizzBuzz"
    { true, false }  -> "Fizz"
    { false, true }  -> "Buzz"
    { false, false } -> x
  end)
end


package main

import (
    "fmt"
    "strings"
)

var given = strings.Split(`ABCD
CABD
ACDB
DACB
BCDA
ACBD
ADCB
CDAB
DABC
BCAD
CADB
CDBA
CBAD
ABDC
ADBC
BDCA
DCBA
BACD
BADC
BDAC
CBDA
DBCA
DCAB`, "\n")

func main() {
    b := make([]byte, len(given[0]))
    for i := range b {
        m := make(map[byte]int)
        for _, p := range given {
            m[p[i]]++
        }
        for char, count := range m {
            if count&1 == 1 {
                b[i] = char
                break
            }
        }
    }
    fmt.Println(string(b))
}


def fact = { n -> [1,(1..<(n+1)).inject(1) { prod, i -> prod * i }].max() }
def missingPerms
missingPerms = {List elts, List perms ->
    perms.empty ? elts.permutations() : elts.collect { e ->
        def ePerms = perms.findAll { e == it[0] }.collect { it[1..-1] }
        ePerms.size() == fact(elts.size() - 1) ? [] \
            : missingPerms(elts - e, ePerms).collect { [e] + it }
    }.sum()
}


import Html exposing (text)
import List exposing (map)

main =
  [1..100] |> map getWordForNum |> text

getWordForNum num =
  if num % 15 == 0 then
    "FizzBuzz"
  else if num % 3 == 0 then
    "Fizz"
  else if num % 5 == 0 then
    "Buzz"
  else
    String.fromInt num


import Data.List ((\\), permutations, nub)
import Control.Monad (join)

missingPerm
  :: Eq a
  => [[a]] -> [[a]]
missingPerm = (\\) =<< permutations . nub . join

deficientPermsList :: [String]
deficientPermsList =
  [ "ABCD"
  , "CABD"
  , "ACDB"
  , "DACB"
  , "BCDA"
  , "ACBD"
  , "ADCB"
  , "CDAB"
  , "DABC"
  , "BCAD"
  , "CADB"
  , "CDBA"
  , "CBAD"
  , "ABDC"
  , "ADBC"
  , "BDCA"
  , "DCBA"
  , "BACD"
  , "BADC"
  , "BDAC"
  , "CBDA"
  , "DBCA"
  , "DCAB"
  ]

main :: IO ()
main = print $ missingPerm deficientPermsList


link strings    # for permutes

procedure main()
givens := set![ "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB",
                "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"]

every insert(full := set(), permutes("ABCD"))  # generate all permutations
givens := full--givens                         # and difference

write("The difference is : ")
every write(!givens, " ")
end


(defun fizzbuzz (n)
  (cond ((and (zerop (% n 5)) (zerop (% n 3))) "FizzBuzz")
	((zerop (% n 3)) "Fizz")
	((zerop (% n 5)) "Buzz")
	(t n)))

;; loop & print from 0 to 100
(dotimes (i 101)
  (message "%s" (fizzbuzz i)))


permutations=: A.~ [email protected][email protected]#
missingPerms=: -.~ permutations @ {.


import java.util.ArrayList;

import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;

public class FindMissingPermutation {
	public static void main(String[] args) {
		Joiner joiner = Joiner.on("").skipNulls();
		ImmutableSet<String> s = ImmutableSet.of("ABCD", "CABD", "ACDB",
				"DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB",
				"CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC",
				"BDAC", "CBDA", "DBCA", "DCAB");

		for (ArrayList<Character> cs : Utils.Permutations(Lists.newArrayList(
				'A', 'B', 'C', 'D')))
			if (!s.contains(joiner.join(cs)))
				System.out.println(joiner.join(cs));
	}
}


🏁🍇
  🔂 i 🆕⏩ 1 101 1 ❗ 🍇
    ↪ i 🚮 15 🙌 0 🍇
      😀 🔤FizzBuzz🔤 ❗
    🍉
    🙅↪ i 🚮 3 🙌 0 🍇
      😀 🔤Fizz🔤 ❗
    🍉
    🙅↪ i 🚮 5 🙌 0 🍇
      😀 🔤Buzz🔤 ❗
    🍉🙅🍇
      😀 🔤🧲i🧲🔤 ❗
    🍉
  🍉
🍉


permute = function(v, m){ //v1.0
    for(var p = -1, j, k, f, r, l = v.length, q = 1, i = l + 1; --i; q *= i);
    for(x = [new Array(l), new Array(l), new Array(l), new Array(l)], j = q, k = l + 1, i = -1;
        ++i < l; x[2][i] = i, x[1][i] = x[0][i] = j /= --k);
    for(r = new Array(q); ++p < q;)
        for(r[p] = new Array(l), i = -1; ++i < l; !--x[1][i] && (x[1][i] = x[0][i],
            x[2][i] = (x[2][i] + 1) % l), r[p][i] = m ? x[3][i] : v[x[3][i]])
            for(x[3][i] = x[2][i], f = 0; !f; f = !f)
                for(j = i; j; x[3][--j] == x[2][i] && (x[3][i] = x[2][i] = (x[2][i] + 1) % l, f = 1));
    return r;
};

list = [ 'ABCD', 'CABD', 'ACDB', 'DACB', 'BCDA', 'ACBD', 'ADCB', 'CDAB',
        'DABC', 'BCAD', 'CADB', 'CDBA', 'CBAD', 'ABDC', 'ADBC', 'BDCA',
        'DCBA', 'BACD', 'BADC', 'BDAC', 'CBDA', 'DBCA', 'DCAB'];

all = permute(list[0].split('')).map(function(elem) {return elem.join('')});

missing = all.filter(function(elem) {return list.indexOf(elem) == -1});
print(missing);  // ==> DBAC


-spec fizzbuzz() -> Result :: string().
fizzbuzz() ->
    F = fun(N) when N rem 15 == 0 -> "FizzBuzz";
           (N) when N rem 3 == 0  -> "Fizz";
           (N) when N rem 5 == 0  -> "Buzz";
           (N) -> integer_to_list(N)
        end,
    lists:flatten([[F(N)] ++ ["\n"] || N <- lists:seq(1,100)]).


jq -R . Find_the_missing_permutation.txt | jq -s -f Find_the_missing_permutation.jq


using BenchmarkTools, Combinatorics

function missingperm(arr::Vector)
    allperms = String.(permutations(arr[1]))  # revised for type safety
    for perm in allperms
        if perm ∉ arr return perm end
    end
end

arr = ["ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD",
       "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC",
       "CBDA", "DBCA", "DCAB"]
@show missingperm(arr)


   split:{1_'(&x=y)_ x:y,x}

   g: ("ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB")
   g,:(" CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB")
   p: split[g;" "];

   / All permutations of "ABCD"
   perm:{:[1<x;,/(>:'(x,x)#1,x#0)[;0,'1+_f x-1];,!x]}
   p2:[email protected](perm(#a:"ABCD"));

   / Which permutations in p are there in p2?
   p2 _lin p
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1

   / Invert the result
   ~p2 _lin p
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0

   / It's the 20th permutation that is missing
   &~p2 _lin p
,20

   [email protected]&~p2 _lin p
"DBAC"


PROGRAM FIZZ_BUZZ
!
! for rosettacode.org
!
BEGIN
 FOR A=1 TO 100 DO
   IF A MOD 15=0 THEN
      PRINT("FizzBuzz")
   ELSIF A MOD 3=0 THEN
      PRINT("Fizz")
   ELSIF A MOD 5=0 THEN
      PRINT("Buzz")
   ELSE
      PRINT(A)
   END IF
 END FOR
END PROGRAM


// version 1.1.2

fun <T> permute(input: List<T>): List<List<T>> {
    if (input.size == 1) return listOf(input)
    val perms = mutableListOf<List<T>>()
    val toInsert = input[0]
    for (perm in permute(input.drop(1))) {
        for (i in 0..perm.size) {
            val newPerm = perm.toMutableList()
            newPerm.add(i, toInsert)
            perms.add(newPerm)
        }
    }
    return perms
}

fun <T> missingPerms(input: List<T>, perms: List<List<T>>) = permute(input) - perms

fun main(args: Array<String>) {
    val input = listOf('A', 'B', 'C', 'D')
    val strings = listOf(
        "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB",
        "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA",
        "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"
    )
    val perms = strings.map { it.toList() }
    val missing = missingPerms(input, perms)
    if (missing.size == 1)
        print("The missing permutation is ${missing[0].joinToString("")}")
    else {
        println("There are ${missing.size} missing permutations, namely:\n")
        for (perm in missing) println(perm.joinToString(""))
    }
}


include std/utils.e

function fb( atom n )
	sequence fb
	if remainder( n, 15 ) = 0 then
		fb = "FizzBuzz"
	elsif remainder( n, 5 ) = 0 then
		fb = "Fizz"
	elsif remainder( n, 3 ) = 0 then
		fb = "Buzz"
	else
		fb = sprintf( "%d", n )
	end if
	return fb
end function

function fb2( atom n )
	return iif( remainder(n, 15) = 0, "FizzBuzz",
		iif( remainder( n, 5 ) = 0, "Fizz",
		iif( remainder( n, 3) = 0, "Buzz", sprintf( "%d", n ) ) ) )
end function

for i = 1 to 30 do
	printf( 1, "%s ", { fb( i ) } )
end for

puts( 1, "\n" )

for i = 1 to 30 do
	printf( 1, "%s ", { fb2( i ) } )
end for

puts( 1, "\n" )


local permute, tablex = require("pl.permute"), require("pl.tablex")
local permList, pStr = {
    "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB",
    "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA",
    "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"
}
for perm in permute.iter({"A","B","C","D"}) do
    pStr = table.concat(perm)
    if not tablex.find(permList, pStr) then print(pStr) end
end


lst := ["ABCD","CABD","ACDB","DACB","BCDA","ACBD","ADCB","CDAB","DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC","BDCA","DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB"]:
perm := table():
for letter in "ABCD" do
	perm[letter] := 0:
end do:
for item in lst do
	for letter in "ABCD" do
		perm[letter] += StringTools:-FirstFromLeft(letter, item):
	end do:
end do:
print(StringTools:-Join(ListTools:-Flatten([indices(perm)], 4)[sort(map(x->60-x, ListTools:-Flatten([entries(perm)],4)),'output=permutation')], "")):


let fizzbuzz n =
    match n%3 = 0, n%5 = 0 with
    | true, false -> "fizz"
    | false, true -> "buzz"
    | true, true  -> "fizzbuzz"
    | _ -> string n

let printFizzbuzz() =
    [1..100] |> List.iter (fizzbuzz >> printfn "%s")


ProvidedSet = {"ABCD" , "CABD" , "ACDB" , "DACB" , "BCDA" , "ACBD",
"ADCB" , "CDAB", "DABC", "BCAD" , "CADB", "CDBA" , "CBAD" , "ABDC",
"ADBC" , "BDCA",  "DCBA" , "BACD", "BADC", "BDAC" , "CBDA", "DBCA", "DCAB"};

Complement[StringJoin /@ [email protected]@[email protected]#, #] &@ProvidedSet

->{"DBAC"}


function perm = findMissingPerms(list)

    permsList = perms(list(1,:)); %Generate all permutations of the 4 letters
    perm = []; %This is the functions return value if the list is not missing a permutation

    %Normally the rest of this would be vectorized, but because this is
    %done on a vector of strings, the vectorized functions will only access
    %one character at a time. So, in order for this to work we have to use
    %loops.
    for i = (1:size(permsList,1))

        found = false;

        for j = (1:size(list,1))
            if (permsList(i,:) == list(j,:))
                found = true;
                break
            end
        end

        if not(found)
            perm = permsList(i,:);
            return
        end

    end %for
end %fingMissingPerms