import time

struct Birthday {
	month int
	day int
}

fn (b Birthday) str() string {
    return "${time.long_months[b.month-1]} $b.day"
}

fn (b Birthday) month_uniquie_in(bds []Birthday) bool {
    mut count := 0
    for bd in bds {
        if bd.month == b.month {
            count++
        }
    }
    if count == 1 {
        return true
    }
    return false
}

fn (b Birthday) day_unique_in(bds []Birthday) bool {
    mut count := 0
    for bd in bds {
        if bd.day == b.day {
            count++
        }
    }
    if count == 1 {
        return true
    }
    return false
}

fn (b Birthday) month_with_unique_day_in(bds []Birthday) bool {
    for bd in bds {
        if bd.month == b.month && bd.day_unique_in(bds) {
            return true
        }
    }
    return false
}

fn main() {
    choices := [
        Birthday{5, 15}, Birthday{5, 16}, Birthday{5, 19}, Birthday{6, 17}, Birthday{6, 18},
        Birthday{7, 14}, Birthday{7, 16}, Birthday{8, 14}, Birthday{8, 15}, Birthday{8, 17},
	]

    // Albert knows the month but doesn't know the day.
    // So the month can't be unique within the choices.
    mut filtered := []Birthday{}
    for bd in choices {
        if !bd.month_uniquie_in(choices) {
            filtered << bd
        }
    }

    // Albert also knows that Bernard doesn't know the answer.
    // So the month can't have a unique day.
    mut filtered2 := []Birthday{}
    for bd in filtered {
        if !bd.month_with_unique_day_in(filtered) {
            filtered2 << bd
        }
    }

    // Bernard now knows the answer.
    // So the day must be unique within the remaining choices.
    mut filtered3 := []Birthday{}
    for bd in filtered2 {
        if bd.day_unique_in(filtered2) {
            filtered3 << bd
        }
    }

    // Albert now knows the answer too.
    // So the month must be unique within the remaining choices.
    mut filtered4 := []Birthday{}
    for bd in filtered3 {
        if bd.month_uniquie_in(filtered3) {
            filtered4 << bd
        }
    }

    if filtered4.len == 1 {
        println("Cheryl's Birthday is ${filtered4[0]}")
    } else {
        println("Something went wrong!")
    }
}


var Months = [
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
]

class Birthday {
    construct new(month, day) {
        _month = month
        _day = day
    }

    month { _month }
    day   { _day }

    toString { "%(Months[_month-1]) %(day)" }

    monthUniqueIn(bds) { bds.count { |bd| _month == bd.month } == 1 }

    dayUniqueIn(bds)   { bds.count { |bd| _day == bd.day } == 1 }

    monthWithUniqueDayIn(bds) { bds.any { |bd| (_month == bd.month) && bd.dayUniqueIn(bds) } }
}

var choices = [
    Birthday.new(5, 15), Birthday.new(5, 16), Birthday.new(5, 19), Birthday.new(6, 17),
    Birthday.new(6, 18), Birthday.new(7, 14), Birthday.new(7, 16), Birthday.new(8, 14),
    Birthday.new(8, 15), Birthday.new(8, 17)
]

// Albert knows the month but doesn't know the day.
// So the month can't be unique within the choices.
var filtered = choices.where { |bd| !bd.monthUniqueIn(choices) }.toList

// Albert also knows that Bernard doesn't know the answer.
// So the month can't have a unique day.
filtered = filtered.where { |bd| !bd.monthWithUniqueDayIn(filtered) }.toList

// Bernard now knows the answer.
// So the day must be unique within the remaining choices.
filtered = filtered.where { |bd| bd.dayUniqueIn(filtered) }.toList

// Albert now knows the answer too.
// So the month must be unique within the remaining choices.
filtered = filtered.where { |bd| bd.monthUniqueIn(filtered) }.toList

if (filtered.count == 1) {
    System.print("Cheryl's birthday is %(filtered[0])")
} else {
    System.print("Something went wrong!")
}


      DIM m1(2,2)
      m1() = 25, 15, -5, \
      \      15, 18,  0, \
      \      -5,  0, 11
      PROCcholesky(m1())
      PROCprint(m1())
      PRINT

      @% = &2050A
      DIM m2(3,3)
      m2() = 18, 22,  54,  42, \
      \      22, 70,  86,  62, \
      \      54, 86, 174, 134, \
      \      42, 62, 134, 106
      PROCcholesky(m2())
      PROCprint(m2())
      END

      DEF PROCcholesky(a())
      LOCAL i%, j%, k%, l(), s
      DIM l(DIM(a(),1),DIM(a(),2))
      FOR i% = 0 TO DIM(a(),1)
        FOR j% = 0 TO i%
          s = 0
          FOR k% = 0 TO j%-1
            s += l(i%,k%) * l(j%,k%)
          NEXT
          IF i% = j% THEN
            l(i%,j%) = SQR(a(i%,i%) - s)
          ELSE
            l(i%,j%) = (a(i%,j%) - s) / l(j%,j%)
          ENDIF
        NEXT j%
      NEXT i%
      a() = l()
      ENDPROC

      DEF PROCprint(a())
      LOCAL row%, col%
      FOR row% = 0 TO DIM(a(),1)
        FOR col% = 0 TO DIM(a(),2)
          PRINT a(row%,col%);
        NEXT
        PRINT
      NEXT row%
      ENDPROC


#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double *cholesky(double *A, int n) {
    double *L = (double*)calloc(n * n, sizeof(double));
    if (L == NULL)
        exit(EXIT_FAILURE);

    for (int i = 0; i < n; i++)
        for (int j = 0; j < (i+1); j++) {
            double s = 0;
            for (int k = 0; k < j; k++)
                s += L[i * n + k] * L[j * n + k];
            L[i * n + j] = (i == j) ?
                           sqrt(A[i * n + i] - s) :
                           (1.0 / L[j * n + j] * (A[i * n + j] - s));
        }

    return L;
}

void show_matrix(double *A, int n) {
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++)
            printf("%2.5f ", A[i * n + j]);
        printf("\n");
    }
}

int main() {
    int n = 3;
    double m1[] = {25, 15, -5,
                   15, 18,  0,
                   -5,  0, 11};
    double *c1 = cholesky(m1, n);
    show_matrix(c1, n);
    printf("\n");
    free(c1);

    n = 4;
    double m2[] = {18, 22,  54,  42,
                   22, 70,  86,  62,
                   54, 86, 174, 134,
                   42, 62, 134, 106};
    double *c2 = cholesky(m2, n);
    show_matrix(c2, n);
    free(c2);

    return 0;
}


dates:=T(T("May",   15), T("May",   16), T("May",   19),
         T("June",  17), T("June",  18),
	 T("July",  14), T("July",  16),
	 T("August",14), T("August",15), T("August",17) );
mDs:=dates.pump(Dictionary().appendKV); // "June":(15,16,19), ...
dMs:=dates.pump(Dictionary().appendKV,"reverse"); // 15:"May", 16:"May", 19:"May", ...

// remove unique days (18,19) --> "July":(14,16),"August":(14,15,17)
dMs.values.apply2('wrap(ms){ if(ms.len()==1) mDs.del(ms[0]) });

// find intersection of above days --> (14)
fcn intersection(l1,l2){ l1.pump(List,l2.holds,'==(True),Void.Filter) }
badDs:=mDs.values.reduce(intersection);

// --> July:(16),August:(15,17) --> ( ("July",(16)) )
theDay:=mDs.filter('wrap([(m,ds)]){ ds.removeEach(badDs).len()==1 });

// print birthday such that muliples are shown, if any
println("Cheryl's birthday is ",theDay.flatten().flatten().concat(" "));


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Cholesky
{
    class Program
    {
        /// <summary>
        /// This is example is written in C#, and compiles with .NET Framework 4.0
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            double[,] test1 = new double[,]
            {
                {25, 15, -5},
                {15, 18, 0},
                {-5, 0, 11},
            };

            double[,] test2 = new double[,]
            {
                {18, 22, 54, 42},
                {22, 70, 86, 62},
                {54, 86, 174, 134},
                {42, 62, 134, 106},
            };

            double[,] chol1 = Cholesky(test1);
            double[,] chol2 = Cholesky(test2);

            Console.WriteLine("Test 1: ");
            Print(test1);
            Console.WriteLine("");
            Console.WriteLine("Lower Cholesky 1: ");
            Print(chol1);
            Console.WriteLine("");
            Console.WriteLine("Test 2: ");
            Print(test2);
            Console.WriteLine("");
            Console.WriteLine("Lower Cholesky 2: ");
            Print(chol2);

        }

        public static void Print(double[,] a)
        {
            int n = (int)Math.Sqrt(a.Length);

            StringBuilder sb = new StringBuilder();
            for (int r = 0; r < n; r++)
            {
                string s = "";
                for (int c = 0; c < n; c++)
                {
                    s += a[r, c].ToString("f5").PadLeft(9) + ",";
                }
                sb.AppendLine(s);
            }

            Console.WriteLine(sb.ToString());
        }

        /// <summary>
        /// Returns the lower Cholesky Factor, L, of input matrix A.
        /// Satisfies the equation: L*L^T = A.
        /// </summary>
        /// <param name="a">Input matrix must be square, symmetric,
        /// and positive definite. This method does not check for these properties,
        /// and may produce unexpected results of those properties are not met.</param>
        /// <returns></returns>
        public static double[,] Cholesky(double[,] a)
        {
            int n = (int)Math.Sqrt(a.Length);

            double[,] ret = new double[n, n];
            for (int r = 0; r < n; r++)
                for (int c = 0; c <= r; c++)
                {
                    if (c == r)
                    {
                        double sum = 0;
                        for (int j = 0; j < c; j++)
                        {
                            sum += ret[c, j] * ret[c, j];
                        }
                        ret[c, c] = Math.Sqrt(a[c, c] - sum);
                    }
                    else
                    {
                        double sum = 0;
                        for (int j = 0; j < c; j++)
                            sum += ret[r, j] * ret[c, j];
                        ret[r, c] = 1.0 / ret[c, c] * (a[r, c] - sum);
                    }
                }

            return ret;
        }
    }
}


#include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <vector>

template <typename scalar_type> class matrix {
public:
    matrix(size_t rows, size_t columns)
        : rows_(rows), columns_(columns), elements_(rows * columns) {}

    matrix(size_t rows, size_t columns, scalar_type value)
        : rows_(rows), columns_(columns), elements_(rows * columns, value) {}

    matrix(size_t rows, size_t columns,
        const std::initializer_list<std::initializer_list<scalar_type>>& values)
        : rows_(rows), columns_(columns), elements_(rows * columns) {
        assert(values.size() <= rows_);
        size_t i = 0;
        for (const auto& row : values) {
            assert(row.size() <= columns_);
            std::copy(begin(row), end(row), &elements_[i]);
            i += columns_;
        }
    }

    size_t rows() const { return rows_; }
    size_t columns() const { return columns_; }

    const scalar_type& operator()(size_t row, size_t column) const {
        assert(row < rows_);
        assert(column < columns_);
        return elements_[row * columns_ + column];
    }
    scalar_type& operator()(size_t row, size_t column) {
        assert(row < rows_);
        assert(column < columns_);
        return elements_[row * columns_ + column];
    }
private:
    size_t rows_;
    size_t columns_;
    std::vector<scalar_type> elements_;
};

template <typename scalar_type>
void print(std::ostream& out, const matrix<scalar_type>& a) {
    size_t rows = a.rows(), columns = a.columns();
    out << std::fixed << std::setprecision(5);
    for (size_t row = 0; row < rows; ++row) {
        for (size_t column = 0; column < columns; ++column) {
            if (column > 0)
                out << ' ';
            out << std::setw(9) << a(row, column);
        }
        out << '\n';
    }
}

template <typename scalar_type>
matrix<scalar_type> cholesky_factor(const matrix<scalar_type>& input) {
    assert(input.rows() == input.columns());
    size_t n = input.rows();
    matrix<scalar_type> result(n, n);
    for (size_t i = 0; i < n; ++i) {
        for (size_t k = 0; k < i; ++k) {
            scalar_type value = input(i, k);
            for (size_t j = 0; j < k; ++j)
                value -= result(i, j) * result(k, j);
            result(i, k) = value/result(k, k);
        }
        scalar_type value = input(i, i);
        for (size_t j = 0; j < i; ++j)
            value -= result(i, j) * result(i, j);
        result(i, i) = std::sqrt(value);
    }
    return result;
}

void print_cholesky_factor(const matrix<double>& matrix) {
    std::cout << "Matrix:\n";
    print(std::cout, matrix);
    std::cout << "Cholesky factor:\n";
    print(std::cout, cholesky_factor(matrix));
}

int main() {
    matrix<double> matrix1(3, 3,
       {{25, 15, -5},
        {15, 18, 0},
        {-5, 0, 11}});
    print_cholesky_factor(matrix1);

    matrix<double> matrix2(4, 4,
       {{18, 22, 54, 42},
        {22, 70, 86, 62},
        {54, 86, 174, 134},
        {42, 62, 134, 106}});
    print_cholesky_factor(matrix2);

    return 0;
}


(defn cholesky
  [matrix]
  (let [n (count matrix)
        A (to-array-2d matrix)
        L (make-array Double/TYPE n n)]
    (doseq [i (range n) j (range (inc i))]
      (let [s (reduce + (for [k (range j)] (* (aget L i k) (aget L j k))))]
        (aset L i j (if (= i j)
                      (Math/sqrt (- (aget A i i) s))
                      (* (/ 1.0 (aget L j j)) (- (aget A i j) s))))))
    (vec (map vec L))))


;; Calculates the Cholesky decomposition matrix L
;; for a positive-definite, symmetric nxn matrix A.
(defun chol (A)
  (let* ((n (car (array-dimensions A)))
         (L (make-array `(,n ,n) :initial-element 0)))

    (do ((k 0 (incf k))) ((> k (- n 1)) nil)
        ;; First, calculate diagonal elements L_kk.
        (setf (aref L k k)
              (sqrt (- (aref A k k)
                       (do* ((j 0 (incf j))
                             (sum (expt (aref L k j) 2)
                                  (incf sum (expt (aref L k j) 2))))
                            ((> j (- k 1)) sum)))))

        ;; Then, all elements below a diagonal element, L_ik, i=k+1..n.
        (do ((i (+ k 1) (incf i)))
            ((> i (- n 1)) nil)

            (setf (aref L i k)
                  (/ (- (aref A i k)
                        (do* ((j 0 (incf j))
                              (sum (* (aref L i j) (aref L k j))
                                   (incf sum (* (aref L i j) (aref L k j)))))
                             ((> j (- k 1)) sum)))
                     (aref L k k)))))

    ;; Return the calculated matrix L.
    L))


function Cholesky(a : array of Float) : array of Float;
var
   i, j, k, n : Integer;
   s : Float;
begin
   n:=Round(Sqrt(a.Length));
   Result:=new Float[n*n];
   for i:=0 to n-1 do begin
      for j:=0 to i do begin
         s:=0 ;
         for k:=0 to j-1 do
            s+=Result[i*n+k] * Result[j*n+k];
         if i=j then
            Result[i*n+j]:=Sqrt(a[i*n+i]-s)
         else Result[i*n+j]:=1/Result[j*n+j]*(a[i*n+j]-s);
      end;
   end;
end;

procedure ShowMatrix(a : array of Float);
var
   i, j, n : Integer;
begin
   n:=Round(Sqrt(a.Length));
   for i:=0 to n-1 do begin
      for j:=0 to n-1 do
         Print(Format('%2.5f ', [a[i*n+j]]));
      PrintLn('');
   end;
end;

var m1 := new Float[9];
m1 := [ 25.0, 15.0, -5.0,
        15.0, 18.0,  0.0,
        -5.0,  0.0, 11.0 ];
var c1 := Cholesky(m1);
ShowMatrix(c1);

PrintLn('');

var m2 : array of Float := [ 18.0, 22.0,  54.0,  42.0,
                             22.0, 70.0,  86.0,  62.0,
                             54.0, 86.0, 174.0, 134.0,
                             42.0, 62.0, 134.0, 106.0 ];
var c2 := Cholesky(m2);
ShowMatrix(c2);


open Microsoft.FSharp.Collections

let cholesky a =
    let calc (a: float[,]) (l: float[,]) i j =
        let c1 j =
            let sum = List.sumBy (fun k -> l.[j, k] ** 2.0) [0..j - 1]
            sqrt (a.[j, j] - sum)
        let c2 i j =
            let sum = List.sumBy (fun k -> l.[i, k] * l.[j, k]) [0..j - 1]
            (1.0 / l.[j, j]) * (a.[i, j] - sum)
        if j > i then 0.0 else
            if i = j
            then c1 j
            else c2 i j
    let l = Array2D.zeroCreate (Array2D.length1 a) (Array2D.length2 a)
    Array2D.iteri (fun i j _ -> l.[i, j] <- calc a l i j) l
    l

let printMat a =
    let arrow = (Array2D.length2 a |> float) / 2.0 |> int
    let c = cholesky a
    for row in 0..(Array2D.length1 a) - 1 do
        for col in 0..(Array2D.length2 a) - 1 do
            printf "%.5f,\t" a.[row, col]
        printf (if arrow = row then "--> \t" else "\t\t")
        for col in 0..(Array2D.length2 c) - 1 do
            printf "%.5f,\t" c.[row, col]
        printfn ""

let ex1 = array2D [
    [25.0; 15.0; -5.0];
    [15.0; 18.0; 0.0];
    [-5.0; 0.0; 11.0]]

let ex2 = array2D [
    [18.0; 22.0; 54.0; 42.0];
    [22.0; 70.0; 86.0; 62.0];
    [54.0; 86.0; 174.0; 134.0];
    [42.0; 62.0; 134.0; 106.0]]

printfn "ex1:"
printMat ex1

printfn "ex2:"
printMat ex2


**
** Cholesky decomposition
**

class Main
{
  // create an array of Floats, initialised to 0.0
  Float[][] makeArray (Int i, Int j)
  {
    Float[][] result := [,]
    i.times { result.add ([,]) }
    i.times |Int x|
    {
      j.times
      {
        result[x].add(0f)
      }
    }
    return result
  }

  // perform the Cholesky decomposition
  Float[][] cholesky (Float[][] array)
  {
    m := array.size
    Float[][] l := makeArray (m, m)
    m.times |Int i|
    {
      (i+1).times |Int k|
      {
        Float sum := (0..<k).toList.reduce (0f) |Float a, Int j -> Float|
        {
          a + l[i][j] * l[k][j]
        }
        if (i == k)
          l[i][k] = (array[i][i]-sum).sqrt
        else
          l[i][k] = (1.0f / l[k][k]) * (array[i][k] - sum)
      }
    }
    return l
  }

  Void runTest (Float[][] array)
  {
    echo (array)
    echo (cholesky (array))
  }

  Void main ()
  {
    runTest ([[25f,15f,-5f],[15f,18f,0f],[-5f,0f,11f]])
    runTest ([[18f,22f,54f,42f],[22f,70f,86f,62f],[54f,86f,174f,134f],[42f,62f,134f,106f]])
  }
}


Program Cholesky_decomp
! *************************************************!
! LBH @ ULPGC 06/03/2014
! Compute the Cholesky decomposition for a matrix A
! after the attached
! http://rosettacode.org/wiki/Cholesky_decomposition
! note that the matrix A is complex since there might
! be values, where the sqrt has complex solutions.
! Here, only the real values are taken into account
!*************************************************!
implicit none

INTEGER, PARAMETER :: m=3 !rows
INTEGER, PARAMETER :: n=3 !cols
COMPLEX, DIMENSION(m,n) :: A
REAL, DIMENSION(m,n) :: L
REAL :: sum1, sum2
INTEGER i,j,k

! Assign values to the matrix
A(1,:)=(/ 25,  15,  -5 /)
A(2,:)=(/ 15,  18,   0 /)
A(3,:)=(/ -5,   0,  11 /)
! !!!!!!!!!!!another example!!!!!!!
! A(1,:) = (/ 18,  22,   54,   42 /)
! A(2,:) = (/ 22,  70,   86,   62 /)
! A(3,:) = (/ 54,  86,  174,  134 /)
! A(4,:) = (/ 42,  62,  134,  106 /)

! Initialize values
L(1,1)=real(sqrt(A(1,1)))
L(2,1)=A(2,1)/L(1,1)
L(2,2)=real(sqrt(A(2,2)-L(2,1)*L(2,1)))
L(3,1)=A(3,1)/L(1,1)
! for greater order than m,n=3 add initial row value
! for instance if m,n=4 then add the following line
! L(4,1)=A(4,1)/L(1,1)

do i=1,n
    do k=1,i
        sum1=0
        sum2=0
        do j=1,k-1
        if (i==k) then
            sum1=sum1+(L(k,j)*L(k,j))
            L(k,k)=real(sqrt(A(k,k)-sum1))
        elseif (i > k) then
            sum2=sum2+(L(i,j)*L(k,j))
            L(i,k)=(1/L(k,k))*(A(i,k)-sum2)
        else
            L(i,k)=0
        end if
        end do
    end do
end do

! write output
do i=1,m
    print "(3(1X,F6.1))",L(i,:)
end do

End program Cholesky_decomp


' version 18-01-2017
' compile with: fbc -s console

Sub Cholesky_decomp(array() As Double)

    Dim As Integer i, j, k
    Dim As Double s, l(UBound(array), UBound(array, 2))

    For i = 0 To UBound(array)
        For j = 0 To i
            s = 0
            For k = 0 To j -1
                s += l(i, k) * l(j, k)
            Next
            If i = j Then
                l(i, j) = Sqr(array(i, i) - s)
            Else
                l(i, j) = (array(i, j) - s) / l(j, j)
            End If
        Next
    Next

    For i = 0 To UBound(array)
        For j = 0 To UBound(array, 2)
            Swap array(i, j), l(i, j)
        Next
    Next

End Sub

Sub Print_(array() As Double)

    Dim As Integer i, j

    For i = 0 To UBound(array)
        For j = 0 To UBound(array, 2)
            Print Using "###.#####";array(i,j);
        Next
        Print
    Next

End Sub

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

Dim  m1(2,2) As Double  => {{25, 15, -5}, _
                            {15, 18,  0}, _
                            {-5,  0, 11}}

Dim m2(3, 3) As Double => {{18, 22,  54,  42}, _
                           {22, 70,  86,  62}, _
                           {54, 86, 174, 134}, _
                           {42, 62, 134, 106}}

Cholesky_decomp(m1())
Print_(m1())

Print
Cholesky_decomp(m2())
Print_(m2())

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


package main

import (
    "fmt"
    "math"
)

// symmetric and lower use a packed representation that stores only
// the lower triangle.

type symmetric struct {
    order int
    ele   []float64
}

type lower struct {
    order int
    ele   []float64
}

// symmetric.print prints a square matrix from the packed representation,
// printing the upper triange as a transpose of the lower.
func (s *symmetric) print() {
    const eleFmt = "%10.5f "
    row, diag := 1, 0
    for i, e := range s.ele {
        fmt.Printf(eleFmt, e)
        if i == diag {
            for j, col := diag+row, row; col < s.order; j += col {
                fmt.Printf(eleFmt, s.ele[j])
                col++
            }
            fmt.Println()
            row++
            diag += row
        }
    }
}

// lower.print prints a square matrix from the packed representation,
// printing the upper triangle as all zeros.
func (l *lower) print() {
    const eleFmt = "%10.5f "
    row, diag := 1, 0
    for i, e := range l.ele {
        fmt.Printf(eleFmt, e)
        if i == diag {
            for j := row; j < l.order; j++ {
                fmt.Printf(eleFmt, 0.)
            }
            fmt.Println()
            row++
            diag += row
        }
    }
}

// choleskyLower returns the cholesky decomposition of a symmetric real
// matrix.  The matrix must be positive definite but this is not checked.
func (a *symmetric) choleskyLower() *lower {
    l := &lower{a.order, make([]float64, len(a.ele))}
    row, col := 1, 1
    dr := 0 // index of diagonal element at end of row
    dc := 0 // index of diagonal element at top of column
    for i, e := range a.ele {
        if i < dr {
            d := (e - l.ele[i]) / l.ele[dc]
            l.ele[i] = d
            ci, cx := col, dc
            for j := i + 1; j <= dr; j++ {
                cx += ci
                ci++
                l.ele[j] += d * l.ele[cx]
            }
            col++
            dc += col
        } else {
            l.ele[i] = math.Sqrt(e - l.ele[i])
            row++
            dr += row
            col = 1
            dc = 0
        }
    }
    return l
}

func main() {
    demo(&symmetric{3, []float64{
        25,
        15, 18,
        -5, 0, 11}})
    demo(&symmetric{4, []float64{
        18,
        22, 70,
        54, 86, 174,
        42, 62, 134, 106}})
}

func demo(a *symmetric) {
    fmt.Println("A:")
    a.print()
    fmt.Println("L:")
    a.choleskyLower().print()
}


def decompose = { a ->
    assert a.size > 0 && a[0].size == a.size
    def m = a.size
    def l = [].withEagerDefault { [].withEagerDefault { 0 } }
    (0..<m).each { i ->
        (0..i).each { k ->
            Number s = (0..<k).sum { j -> l[i][j] * l[k][j] } ?: 0
            l[i][k] = (i == k)
                        ? Math.sqrt(a[i][i] - s)
                        : (1.0 / l[k][k] * (a[i][k] - s))
        }
    }
    l
}


module Cholesky (Arr, cholesky) where

import Data.Array.IArray
import Data.Array.MArray
import Data.Array.Unboxed
import Data.Array.ST

type Idx = (Int,Int)
type Arr = UArray Idx Double

-- Return the (i,j) element of the lower triangular matrix.  (We assume the
-- lower array bound is (0,0).)
get :: Arr -> Arr -> Idx -> Double
get a l (i,j) | i == j = sqrt $ a!(j,j) - dot
              | i  > j = (a!(i,j) - dot) / l!(j,j)
              | otherwise = 0
  where dot = sum [l!(i,k) * l!(j,k) | k <- [0..j-1]]

-- Return the lower triangular matrix of a Cholesky decomposition.  We assume
-- the input is a real, symmetric, positive-definite matrix, with lower array
-- bounds of (0,0).
cholesky :: Arr -> Arr
cholesky a = let n = maxBnd a
             in runSTUArray $ do
               l <- thaw a
               mapM_ (update a l) [(i,j) | i <- [0..n], j <- [0..n]]
               return l
  where maxBnd = fst . snd . bounds
        update a l i = unsafeFreeze l >>= \l' -> writeArray l i (get a l' i)


procedure cholesky (array)
  result := make_square_array (*array)
  every (i := 1 to *array) do {
    every (k := 1 to i) do {
      sum := 0
      every (j := 1 to (k-1)) do {
        sum +:= result[i][j] * result[k][j]
      }
      if (i = k)
        then result[i][k] := sqrt(array[i][i] - sum)
        else result[i][k] := 1.0 / result[k][k] * (array[i][k] - sum)
    }
  }
  return result
end

procedure make_square_array (n)
  result := []
  every (1 to n) do push (result, list(n, 0))
  return result
end

procedure print_array (array)
  every (row := !array) do {
    every writes (!row || " ")
    write ()
  }
end

procedure do_cholesky (array)
  write ("Input:")
  print_array (array)
  result := cholesky (array)
  write ("Result:")
  print_array (result)
end

procedure main ()
  do_cholesky ([[25,15,-5],[15,18,0],[-5,0,11]])
  do_cholesky ([[18,22,54,42],[22,70,86,62],[54,86,174,134],[42,62,134,106]])
end


module Main

import Data.Vect

Matrix : Nat -> Nat -> Type -> Type
Matrix m n t = Vect m (Vect n t)

zeros : (m : Nat) -> (n : Nat) -> Matrix m n Double
zeros m n = replicate m (replicate n 0.0)

indexM : (Fin m, Fin n) -> Matrix m n t -> t
indexM (i, j) a = index j (index i a)

replaceAtM : (Fin m, Fin n) -> t -> Matrix m n t -> Matrix m n t
replaceAtM (i, j) e a = replaceAt i (replaceAt j e (index i a)) a

get : Matrix m m Double -> Matrix m m Double -> (Fin m, Fin m) -> Double
get a l (i, j) {m} =  if i == j then sqrt $ indexM (j, j) a - dot
             else if i > j  then (indexM (i, j) a - dot) / indexM (j, j) l
             else 0.0

  where
        -- Obtain indicies 0 to j -1
        ks : List (Fin m)
        ks = case (findIndices (\_ => True) a) of
          [] => []
          (x::xs) => init (x::xs)

        dot : Double
        dot = sum [(indexM (i, k) l) * (indexM (j, k) l) | k <- ks]

updateL : Matrix m m Double -> Matrix m m Double -> (Fin m, Fin m) -> Matrix m m Double
updateL a l idx = replaceAtM idx (get a l idx) l

cholesky : Matrix m m Double -> Matrix m m Double
cholesky a {m} =
    foldl (\l',i =>
        foldl (\l'',j => updateL a l'' (i, j)) l' (js i))
          l is
  where  l = zeros m m

         is : List (Fin m)
         is = findIndices (\_ => True) a

         js : Fin m -> List (Fin m)
         js n = filter (<= n) is

ex1 : Matrix 3 3 Double
ex1 = cholesky [[25.0, 15.0, -5.0], [15.0, 18.0, 0.0], [-5.0, 0.0, 11.0]]

ex2 : Matrix 4 4 Double
ex2 = cholesky [[18.0, 22.0, 54.0, 42.0], [22.0, 70.0, 86.0, 62.0],
                [54.0, 86.0, 174.0, 134.0], [42.0, 62.0, 134.0, 106.0]]

main : IO ()
main = do
  print ex1
  putStrLn "\n"
  print ex2
  putStrLn "\n"


mp=: +/ . *  NB. matrix product
h =: [email protected]|:    NB. conjugate transpose

cholesky=: 3 : 0
 n=. #A=. y
 if. 1>:n do.
  assert. (A=|A)>0=A  NB. check for positive definite
  %:A
 else.
  'X Y t Z'=. , (;~n$(>.-:n){.1) <;.1 A
  L0=. cholesky X
  L1=. cholesky Z-(T=.(h Y) mp %.X) mp Y
  L0,(T mp L0),.L1
 end.
)


import java.util.Arrays;

public class Cholesky {
	public static double[][] chol(double[][] a){
		int m = a.length;
		double[][] l = new double[m][m]; //automatically initialzed to 0's
		for(int i = 0; i< m;i++){
			for(int k = 0; k < (i+1); k++){
				double sum = 0;
				for(int j = 0; j < k; j++){
					sum += l[i][j] * l[k][j];
				}
				l[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) :
					(1.0 / l[k][k] * (a[i][k] - sum));
			}
		}
		return l;
	}

	public static void main(String[] args){
		double[][] test1 = {{25, 15, -5},
							{15, 18, 0},
							{-5, 0, 11}};
		System.out.println(Arrays.deepToString(chol(test1)));
		double[][] test2 = {{18, 22, 54, 42},
							{22, 70, 86, 62},
							{54, 86, 174, 134},
							{42, 62, 134, 106}};
		System.out.println(Arrays.deepToString(chol(test2)));
	}
}


fs:is_file(‘input.txt’)
fs:is_file(‘/input.txt’)
fs:is_dir(‘docs’)
fs:is_dir(‘/docs’)


const cholesky = function (array) {
	const zeros = [...Array(array.length)].map( _ => Array(array.length).fill(0));
	const L = zeros.map((row, r, xL) => row.map((v, c) => {
		const sum = row.reduce((s, _, i) => i < c ? s + xL[r][i] * xL[c][i] : s, 0);
		return xL[r][c] = c < r + 1 ? r === c ? Math.sqrt(array[r][r] - sum) : (array[r][c] - sum) / xL[c][c] : v;
	}));
	return L;
}

let arr3 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]];
console.log(cholesky(arr3));
let arr4 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]];
console.log(cholesky(arr4));


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program verifFic64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ CHDIR,   49
.equ AT_FDCWD,    -100

/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessFound1:     .asciz "File 1 found.\n"
szMessFound2:     .asciz "File 2 found.\n"
szMessNotFound1:  .asciz "File 1 not found.\n"
szMessNotFound2:  .asciz "File 2 not found.\n"
szMessDir2:       .asciz "File 2 is a directory.\n"
szMessNotAuth2:   .asciz "File 2 permission denied.\n"
szCarriageReturn: .asciz "\n"

/* areas strings  */
szPath2:          .asciz "/"
szFicName1:       .asciz "test1.txt"
szFicName2:       .asciz "root"

/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main
main:                        // entry of program

    /*************************************
     open file 1
    ************************************/
    mov x0,AT_FDCWD          // current directory
    ldr x1,qAdrszFicName1    // file name
    mov x2,#O_RDWR           // flags
    mov x3,#0                // mode
    mov x8, #OPEN            // call system OPEN
    svc 0
    cmp x0,#0                // error ?
    ble 1f
    mov x1,x0                // FD
    ldr x0,qAdrszMessFound1
    bl affichageMess
                             // close file
    mov x0,x1                // Fd
    mov x8, #CLOSE
    svc 0
    b 2f
1:
    ldr x0,qAdrszMessNotFound1
    bl affichageMess
2:
    /*************************************
     open file 2
    ************************************/
    ldr x0,qAdrszPath2
    mov x8,CHDIR            // call system change directory
    svc 0
    mov x0,AT_FDCWD         // current directory
    ldr x1,qAdrszFicName2   // file name
    mov x2,O_RDWR           //  flags
    mov x3,0                // mode
    mov x8,OPEN             // call system OPEN
    svc 0
    cmp x0,-21              // is a directory ?
    beq 4f
    cmp x0,0                // error ?
    ble 3f
    mov x1,x0               // FD
    ldr x0,qAdrszMessFound2
    bl affichageMess
                            // close file
    mov x0,x1               // Fd
    mov x8, #CLOSE
    svc 0
    b 100f
3:
    ldr x0,qAdrszMessNotFound2
    bl affichageMess
    b 100f
4:
    ldr x0,qAdrszMessDir2
    bl affichageMess
100:                           // standard end of the program
    mov x0,0                   // return code
    mov x8,EXIT                // request to exit program
    svc 0                      // perform the system call
qAdrszFicName1:            .quad szFicName1
qAdrszFicName2:            .quad szFicName2
qAdrszMessFound1:          .quad szMessFound1
qAdrszMessFound2:          .quad szMessFound2
qAdrszMessNotFound1:       .quad szMessNotFound1
qAdrszMessNotFound2:       .quad szMessNotFound2
qAdrszMessNotAuth2:        .quad szMessNotAuth2
qAdrszPath2:               .quad szPath2
qAdrszMessDir2:            .quad szMessDir2
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


BYTE lastError

PROC MyError(BYTE errCode)
  lastError=errCode
RETURN

BYTE FUNC FileExists(CHAR ARRAY fname)
  DEFINE PTR="CARD"
  PTR old
  BYTE dev=[1]

  lastError=0
  old=Error
  Error=MyError ;replace error handling to capture I/O error

  Close(dev)
  Open(dev,fname,4)
  Close(dev)

  Error=old ;restore the original error handling

  IF lastError=0 THEN
    RETURN (1)
  FI
RETURN (0)

PROC Test(CHAR ARRAY fname)
  BYTE exists

  exists=FileExists(fname)
  IF exists THEN
    PrintF("File ""%S"" exists.%E",fname)
  ELSE
    PrintF("File ""%S"" does not exist.%E",fname)
  FI
RETURN

PROC Main()
  Test("D:INPUT.TXT")
  Test("D:DOS.SYS")
RETURN


with Ada.Text_IO; use Ada.Text_IO;

procedure File_Exists is
   function Does_File_Exist (Name : String) return Boolean is
      The_File : Ada.Text_IO.File_Type;
   begin
      Open (The_File, In_File, Name);
      Close (The_File);
      return True;
   exception
      when Name_Error =>
         return False;
   end Does_File_Exist;
begin
   Put_Line (Boolean'Image (Does_File_Exist ("input.txt" )));
   Put_Line (Boolean'Image (Does_File_Exist ("\input.txt")));
end File_Exists;


function exists (filename) {
    return stat (filename) != null
}

exists ("input.txt")
exists ("/input.txt")
exists ("docs")
exists ("/docs")


# Create an m x n matrix
 def matrix(m; n; init):
   if m == 0 then []
   elif m == 1 then [range(0; n)] | map(init)
   elif m > 0 then
     matrix(1; n; init) as $row
     | [range(0; m)] | map( $row )
   else error("matrix\(m);_;_) invalid")
   end ;

# Print a matrix neatly, each cell ideally occupying n spaces,
# but without truncation
def neatly(n):
  def right: tostring | ( " " * (n-length) + .);
  . as $in
  | length as $length
  | reduce range (0; $length) as $i
      (""; . + reduce range(0; $length) as $j
      (""; "\(.) \($in[$i][$j] | right )" ) + "\n" ) ;

def is_square:
  type == "array" and (map(type == "array") | all) and
    length == 0 or ( (.[0]|length) as $l | map(length == $l) | all) ;

# This implementation of is_symmetric/0 uses a helper function that circumvents
# limitations of jq 1.4:
def is_symmetric:
    # [matrix, i,j, len]
    def test:
       if .[1] > .[3] then true
       elif .[1] == .[2] then [ .[0], .[1] + 1, 0, .[3]] | test
       elif .[0][.[1]][.[2]] == .[0][.[2]][.[1]]
         then [ .[0], .[1], .[2]+1, .[3]] | test
      else false
      end;
    if is_square|not then false
    else [ ., 0, 0, length ] | test
    end ;


// version 1.0.6

fun cholesky(a: DoubleArray): DoubleArray {
    val n = Math.sqrt(a.size.toDouble()).toInt()
    val l = DoubleArray(a.size)
    var s: Double
    for (i in 0 until n)
        for (j in 0 .. i) {
            s = 0.0
            for (k in 0 until j) s += l[i * n + k] * l[j * n + k]
            l[i * n + j] = when {
                (i == j) -> Math.sqrt(a[i * n + i] - s)
                else     -> 1.0 / l[j * n + j] * (a[i * n + j] - s)
            }
        }
    return l
}

fun showMatrix(a: DoubleArray) {
    val n = Math.sqrt(a.size.toDouble()).toInt()
    for (i in 0 until n) {
        for (j in 0 until n) print("%8.5f ".format(a[i * n + j]))
        println()
    }
}

fun main(args: Array<String>) {
    val m1 = doubleArrayOf(25.0, 15.0, -5.0,
                           15.0, 18.0,  0.0,
                           -5.0,  0.0, 11.0)
    val c1 = cholesky(m1)
    showMatrix(c1)
    println()
    val m2 = doubleArrayOf(18.0, 22.0,  54.0,  42.0,
                           22.0, 70.0,  86.0,  62.0,
                           54.0, 86.0, 174.0, 134.0,
                           42.0, 62.0, 134.0, 106.0)
    val c2 = cholesky(m2)
    showMatrix(c2)
}


# Check files and directories exist                               #

# check a file exists by attempting to open it for input          #
# returns TRUE if the file exists, FALSE otherwise                #
PROC file exists = ( STRING file name )BOOL:
    IF  FILE f;
        open( f, file name, stand in channel ) = 0
    THEN
        # file opened OK so must exist                            #
        close( f );
        TRUE
    ELSE
        # file cannot be opened - assume it does not exist        #
        FALSE
    FI # file exists # ;

# print a suitable messages if the specified file exists          #
PROC test file exists = ( STRING name )VOID:
    print( ( "file: "
           , name
           , IF file exists( name ) THEN " does" ELSE " does not" FI
           , " exist"
           , newline
           )
         );
# print a suitable messages if the specified directory exists     #
PROC test directory exists = ( STRING name )VOID:
    print( ( "dir:  "
           , name
           , IF file is directory( name ) THEN " does" ELSE " does not" FI
           , " exist"
           , newline
           )
         );

# test the flies and directories mentioned in the task exist or not #
test file exists( "input.txt" );
test file exists( "\input.txt");
test directory exists( "docs" );
test directory exists( "\docs" )


#include <flow.h>

DEF-MAIN(argv, argc)
   WHEN( IS-FILE?("hopper") ){
      MEM("File \"hopper\" exist!\n")
   }
   WHEN( IS-DIR?("fl") ){
      MEM("Directory \"fl\" exist!\n")
   }
   IF( IS-DIR?("noExisDir"), "Directory \"noExistDir\" exist!\n", \
                             "Directory \"noExistDir\" does NOT exist!\n" )
   //"arch mañoso bacán.txt" text-file created

   STR-TO-UTF8("File \"arch mañoso bacán.txt\" ")
   IF( IS-FILE?( STR-TO-UTF8("arch mañoso bacán.txt") ), "exist!\n", "NOT exist!\n")

   PRNL
END


import std

// choleskyLower returns the cholesky decomposition of a symmetric real
// matrix.  The matrix must be positive definite but this is not checked
def choleskyLower(order, a) -> [float]:
    let l = map(a.length): 0.0
    var row, col = 1, 1
    var dr = 0 // index of diagonal element at end of row
    var dc = 0 // index of diagonal element at top of column
    for(a) e, i:
        if i < dr:
            let d = (e - l[i]) / l[dc]
            l[i] = d
            var ci, cx = col, dc
            var j = i + 1
            while j <= dr:
                cx += ci
                ci += 1
                l[j] += d * l[cx]
                j += 1
            col += 1
            dc += col
        else:
            l[i] = sqrt(e - l[i])
            row += 1
            dr += row
            col = 1
            dc = 0
    return l

// symmetric.print prints a square matrix from the packed representation,
// printing the upper triange as a transpose of the lower
def print_symmetric(order, s):
    //const eleFmt = "%10.5f "
    var str = ""
    var row, diag = 1, 0
    for(s) e, i:
        str += e + " " // format?
        if i == diag:
            var j, col = diag+row, row
            while col < order:
                str += s[j] + " " // format?
                col++
                j += col
            print(str); str = ""
            row += 1
            diag += row

// lower.print prints a square matrix from the packed representation,
// printing the upper triangle as all zeros.
def print_lower(order, l):
    //const eleFmt = "%10.5f "
    var str = ""
    var row, diag = 1, 0
    for(l) e, i:
        str += e + " " // format?
        if i == diag:
            var j = row
            while j < order:
                str += 0.0 + " " // format?
                j += 1
            print(str); str = ""
            row += 1
            diag += row

def demo(order, a):
    print("A:")
    print_symmetric(order, a)
    print("L:")
    print_lower(order, choleskyLower(order, a))

demo(3, [25.0,
         15.0, 18.0,
         -5.0, 0.0, 11.0])

demo(4, [18.0,
         22.0, 70.0,
         54.0, 86.0, 174.0,
         42.0, 62.0, 134.0, 106.0])


use framework "Foundation" -- YOSEMITE OS X onwards
use scripting additions

on run
    setCurrentDirectory("~/Desktop")

    ap({doesFileExist, doesDirectoryExist}, ¬
        {"input.txt", "/input.txt", "docs", "/docs"})

    --> {true, true, true, true, false, false, true, true}

    -- The first four booleans are returned by `doesFileExist`.

    -- The last four are returned by `doesDirectoryExist`,
    -- which yields false for simple files, and true for directories.
end run

-- GENERIC SYSTEM DIRECTORY FUNCTIONS -----------------------------------------

-- doesDirectoryExist :: String -> Bool
on doesDirectoryExist(strPath)
    set ca to current application
    set oPath to (ca's NSString's stringWithString:strPath)'s ¬
        stringByStandardizingPath
    set {bln, int} to (ca's NSFileManager's defaultManager()'s ¬
        fileExistsAtPath:oPath isDirectory:(reference))
    bln and (int = 1)
end doesDirectoryExist

-- doesFileExist :: String -> Bool
on doesFileExist(strPath)
    set ca to current application
    set oPath to (ca's NSString's stringWithString:strPath)'s ¬
        stringByStandardizingPath
    ca's NSFileManager's defaultManager()'s fileExistsAtPath:oPath
end doesFileExist

-- getCurrentDirectory :: String
on getCurrentDirectory()
    set ca to current application
    ca's NSFileManager's defaultManager()'s currentDirectoryPath as string
end getCurrentDirectory

-- getFinderDirectory :: String
on getFinderDirectory()
    tell application "Finder" to POSIX path of (insertion location as alias)
end getFinderDirectory

-- getHomeDirectory :: String
on getHomeDirectory()
    (current application's NSHomeDirectory() as string)
end getHomeDirectory

-- setCurrentDirectory :: String -> IO ()
on setCurrentDirectory(strPath)
    if doesDirectoryExist(strPath) then
        set ca to current application
        set oPath to (ca's NSString's stringWithString:strPath)'s ¬
            stringByStandardizingPath
        ca's NSFileManager's defaultManager()'s ¬
            changeCurrentDirectoryPath:oPath
    end if
end setCurrentDirectory

-- GENERIC HIGHER ORDER FUNCTIONS FOR THE TEST --------------------------------

-- A list of functions applied to a list of arguments
-- (<*> | ap) :: [(a -> b)] -> [a] -> [b]
on ap(fs, xs)
    set {intFs, intXs} to {length of fs, length of xs}
    set lst to {}
    repeat with i from 1 to intFs
        tell mReturn(item i of fs)
            repeat with j from 1 to intXs
                set end of lst to |λ|(contents of (item j of xs))
            end repeat
        end tell
    end repeat
    return lst
end ap

-- 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


100 F$ = "THAT FILE"
110 T$(0) = "DOES NOT EXIST."
120 T$(1) = "EXISTS."
130 GOSUB 200"FILE EXISTS?
140 PRINT F$; " "; T$(E)
150 END

200 REM FILE EXISTS?
210 REM TRY
220    ON ERR GOTO 300"CATCH
230    PRINT CHR$(4); "VERIFY "; F$
240    POKE 216, 0 : REM ONERR OFF
250    E = 1
260    GOTO 350"END TRY
300 REM CATCH
310    E = PEEK(222) <> 6
320    POKE 216, 0 : REM ONERR OFF
330    IF E THEN RESUME : REM THROW
340    CALL  - 3288 : REM RECOVER
350 REM END TRY
360 RETURN


/* ARM assembly Raspberry PI  */
/*  program verifFic.s   */

/* Constantes    */
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ WRITE,  4     @ Linux syscall
.equ OPEN,   5     @ Linux syscall
.equ CLOSE, 6     @ Linux syscall

.equ O_RDWR,	0x0002		/* open for reading and writing */

/*******************************************/
/* Fichier des macros                       */
/********************************************/
.include "../../ficmacros.s"

/* Initialized data */
.data
szMessFound1:     .asciz "File 1 found.\n"
szMessFound2:     .asciz "File 2 found.\n"
szMessNotFound1: .asciz "File 1 not found.\n"
szMessNotFound2: .asciz "File 2 not found.\n"
szMessNotAuth2:   .asciz "File 2 permission denied.\n"
szCarriageReturn: .asciz "\n"

/* areas strings  */
szFicName1:  .asciz "test1.txt"
szFicName2:  .asciz "/debian-binary"

/* UnInitialized data */
.bss

/*  code section */
.text
.global main
main:                /* entry of program  */
    push {fp,lr}    /* saves 2 registers */

    /*************************************
     open file 1
    ************************************/
    ldr r0,iAdrszFicName1    @ file name
    mov r1,#O_RDWR             @ flags
    mov r2,#0                    @ mode
    mov r7, #OPEN               @ call system OPEN
    swi 0
    cmp r0,#0    @ error ?
    ble 1f
    mov r1,r0    @ FD
    ldr r0,iAdrszMessFound1
    bl affichageMess
    @ close file
    mov r0,r1   @ Fd
    mov r7, #CLOSE
    swi 0
    b 2f
1:
    ldr r0,iAdrszMessNotFound1
    bl affichageMess
2:
    /*************************************
     open file 2
    ************************************/
    ldr r0,iAdrszFicName2    @ file name
    mov r1,#O_RDWR   @  flags
    mov r2,#0         @ mode
    mov r7, #OPEN    @ call system OPEN
    swi 0
    vidregtit verif
    cmp r0,#-13    @ permission denied
    beq 4f
    cmp r0,#0    @ error ?
    ble 3f
    mov r1,r0    @ FD
    ldr r0,iAdrszMessFound2
    bl affichageMess
    @ close file
    mov r0,r1   @ Fd
    mov r7, #CLOSE
    swi 0
    b 100f
3:
    ldr r0,iAdrszMessNotFound2
    bl affichageMess
    b 100f
4:
    ldr r0,iAdrszMessNotAuth2
    bl affichageMess
100:   /* standard end of the program */
    mov r0, #0                  @ return code
    pop {fp,lr}                 @restaur 2 registers
    mov r7, #EXIT              @ request to exit program
    swi 0                       @ perform the system call
iAdrszFicName1:			.int szFicName1
iAdrszFicName2:			.int szFicName2
iAdrszMessFound1:		.int szMessFound1
iAdrszMessFound2:		.int szMessFound2
iAdrszMessNotFound1: 	.int szMessNotFound1
iAdrszMessNotFound2: 	.int szMessNotFound2
iAdrszMessNotAuth2:	.int szMessNotAuth2
/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {fp,lr}    			/* save  registres */
    push {r0,r1,r2,r7}    		/* save others registers */
    mov r2,#0   				/* counter length */
1:      	/* loop length calculation */
    ldrb r1,[r0,r2]  			/* read octet start position + index */
    cmp r1,#0       			/* if 0 its over */
    addne r2,r2,#1   			/* else add 1 in the length */
    bne 1b          			/* and loop */
                                /* so here r2 contains the length of the message */
    mov r1,r0        			/* address message in r1 */
    mov r0,#STDOUT      		/* code to write to the standard output Linux */
    mov r7, #WRITE             /* code call system "write" */
    swi #0                      /* call systeme */
    pop {r0,r1,r2,r7}     		/* restaur others registers */
    pop {fp,lr}    				/* restaur des  2 registres */
    bx lr	        			/* return  */


import math, strutils, strformat

type Matrix[N: static int, T: SomeFloat] = array[N, array[N, T]]

proc cholesky[Matrix](a: Matrix): Matrix =
  for i in 0 ..< a[0].len:
    for j in 0 .. i:
      var s = 0.0
      for k in 0 ..< j:
        s += result[i][k] * result[j][k]
      result[i][j] = if i == j: sqrt(a[i][i]-s)
                     else: 1.0 / result[j][j] * (a[i][j] - s)

proc `$`(a: Matrix): string =
  result = ""
  for b in a:
    var line = ""
    for c in b:
      line.addSep(" ", 0)
      line.add fmt"{c:8.5f}"
    result.add line & '\n'

let m1 = [[25.0, 15.0, -5.0],
          [15.0, 18.0,  0.0],
          [-5.0,  0.0, 11.0]]
echo cholesky(m1)

let m2 = [[18.0, 22.0,  54.0,  42.0],
          [22.0, 70.0,  86.0,  62.0],
          [54.0, 86.0, 174.0, 134.0],
          [42.0, 62.0, 134.0, 106.0]]
echo cholesky(m2)


checkIfExists: function [fpath][
    (or? exists? fpath
         exists? .directory fpath)? -> print [fpath "exists"]
                                    -> print [fpath "doesn't exist"]
]

checkIfExists "input.txt"
checkIfExists "docs"

checkIfExists "/input.txt"
checkIfExists "/docs"


; FileExist() function examples
ShowFileExist("input.txt")
ShowFileExist("\input.txt")
ShowFolderExist("docs")
ShowFolderExist("\docs")

; IfExist/IfNotExist command examples (from documentation)
IfExist, D:\
  MsgBox, The drive exists.
IfExist, D:\Docs\*.txt
  MsgBox, At least one .txt file exists.
IfNotExist, C:\Temp\FlagFile.txt
  MsgBox, The target file does not exist.

Return

ShowFileExist(file)
{
  If (FileExist(file) && !InStr(FileExist(file), "D"))
    MsgBox, file: %file% exists.
  Else
    MsgBox, file: %file% does NOT exist.
  Return
}

ShowFolderExist(folder)
{
  If InStr(FileExist(folder), "D")
    MsgBox, folder: %folder% exists.
  Else
    MsgBox, folder: %folder% does NOT exist.
  Return
}


@load "filefuncs"

function exists(name    ,fd) {
    if ( stat(name, fd) == -1)
      print name " doesn't exist"
    else
      print name " exists"
}
BEGIN {
    exists("input.txt")
    exists("/input.txt")
    exists("docs")
    exists("/docs")
}


let cholesky inp =
   let n = Array.length inp in
   let res = Array.make_matrix n n 0.0 in
   let factor i k =
      let rec sum j =
         if j = k then 0.0 else
         res.(i).(j) *. res.(k).(j) +. sum (j+1) in
      inp.(i).(k) -. sum 0 in
   for col = 0 to n-1 do
      res.(col).(col) <- sqrt (factor col col);
      for row = col+1 to n-1 do
         res.(row).(col) <- (factor row col) /. res.(col).(col)
      done
   done;
   res

let pr_vec v = Array.iter (Printf.printf " %9.5f") v; print_newline()
let show = Array.iter pr_vec
let test a =
   print_endline "\nin:"; show a;
   print_endline "out:"; show (cholesky a)

let _ =
   test [| [|25.0; 15.0; -5.0|];
           [|15.0; 18.0;  0.0|];
           [|-5.0;  0.0; 11.0|] |];
   test [| [|18.0; 22.0;  54.0;  42.0|];
           [|22.0; 70.0;  86.0;  62.0|];
           [|54.0; 86.0; 174.0; 134.0|];
           [|42.0; 62.0; 134.0; 106.0|] |];


If GetCalc("appvINPUT")
 Disp "EXISTS",i
Else
 Disp "DOES NOT EXIST",i
End


ON ERROR GOTO ohNo
f$ = "input.txt"
GOSUB opener
f$ = "\input.txt"
GOSUB opener

'can't directly check for directories,
'but can check for the NUL device in the desired dir
f$ = "docs\nul"
GOSUB opener
f$ = "\docs\nul"
GOSUB opener
END

opener:
    e$ = " found"
    OPEN f$ FOR INPUT AS 1
    PRINT f$; e$
    CLOSE
    RETURN

ohNo:
    IF (53 = ERR) OR (76 = ERR) THEN
        e$ = " not" + e$
    ELSE
        e$ = "Unknown error"
    END IF
    RESUME NEXT


subroutine opener (filename$)
    if exists(filename$) then
	print filename$; " exists"
    else
	print filename$; " does not exists"
    end if
end subroutine

call opener ("input.txt")
call opener ("\input.txt")
call opener ("docs\nul")
call opener ("\docs\nul")
call opener ("empty.kbs")
call opener ("`Abdu'l-Bahá.txt"))
end


if exist input.txt echo The following file called input.txt exists.
if exist \input.txt echo The following file called \input.txt exists.
if exist docs echo The following directory called docs exists.
if exist \docs\ echo The following directory called \docs\ exists.


/*REXX program performs the  Cholesky  decomposition  on a square matrix.     */
niner =  '25  15  -5' ,                              /*define a  3x3  matrix. */
         '15  18   0' ,
         '-5   0  11'
                           call Cholesky niner
hexer =  18  22  54  42,                             /*define a  4x4  matrix. */
         22  70  86  62,
         54  86 174 134,
         42  62 134 106
                           call Cholesky hexer
exit                                   /*stick a fork in it,  we're all done. */
/*----------------------------------------------------------------------------*/
Cholesky: procedure;  parse arg mat;   say;   say;   call tell 'input matrix',mat
             do    r=1  for ord
                do c=1  for r; d=0;  do i=1  for c-1; d=d+!.r.i*!.c.i; end /*i*/
                if r=c  then !.r.r=sqrt(!.r.r-d)
                        else !.r.c=1/!.c.c*(a.r.c-d)
                end   /*c*/
             end      /*r*/
          call tell  'Cholesky factor',,!.,'-'
          return
/*----------------------------------------------------------------------------*/
err:   say;  say;  say '***error***!';    say;  say arg(1);  say;  say;  exit 13
/*----------------------------------------------------------------------------*/
tell:  parse arg hdr,x,y,sep;   n=0;             if sep==''  then sep='-'
       dPlaces= 5                    /*n decimal places past the decimal point*/
       width  =10                    /*width of field used to display elements*/
       if y==''  then !.=0
                 else do row=1  for ord; do col=1  for ord; x=x !.row.col; end; end
       w=words(x)
           do ord=1  until ord**2>=w; end  /*a fast way to find matrix's order*/
       say
       if ord**2\==w  then call err  "matrix elements don't form a square matrix."
       say center(hdr, ((width+1)*w)%ord, sep)
       say
               do   row=1  for ord;       z=''
                 do col=1  for ord;       n=n+1
                                    a.row.col=word(x,n)
                 if col<=row  then  !.row.col=a.row.col
                 z=z  right( format(a.row.col,, dPlaces) / 1,   width)
                 end   /*col*/
               say z
               end        /*row*/
       return
/*----------------------------------------------------------------------------*/
sqrt:  procedure; parse arg x;   if x=0  then return 0;  d=digits();  i=''; m.=9
       numeric digits 9; numeric form; h=d+6; if x<0  then  do; x=-x; i='i'; end
       parse value format(x,2,1,,0) 'E0'  with  g 'E' _ .;       g=g*.5'e'_%2
          do j=0  while h>9;      m.j=h;              h=h%2+1;        end  /*j*/
          do k=j+5  to 0  by -1;  numeric digits m.k; g=(g+x/g)*.5;   end  /*k*/
       numeric digits d;     return (g/1)i            /*make complex if X < 0.*/


      test% = OPENIN("input.txt")
      IF test% THEN
        CLOSE #test%
        PRINT "File input.txt exists"
      ENDIF

      test% = OPENIN("\input.txt")
      IF test% THEN
        CLOSE #test%
        PRINT "File \input.txt exists"
      ENDIF

      test% = OPENIN("docs\NUL")
      IF test% THEN
        CLOSE #test%
        PRINT "Directory docs exists"
      ENDIF

      test% = OPENIN("\docs\NUL")
      IF test% THEN
        CLOSE #test%
        PRINT "Directory \docs exists"
      ENDIF


fname ← ⊑args
•Out fname∾" Does not exist"‿" Exists"⊑˜•File.exists fname


#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>

/* Check for regular file. */
int check_reg(const char *path) {
	struct stat sb;
	return stat(path, &sb) == 0 && S_ISREG(sb.st_mode);
}

/* Check for directory. */
int check_dir(const char *path) {
	struct stat sb;
	return stat(path, &sb) == 0 && S_ISDIR(sb.st_mode);
}

int main() {
	printf("input.txt is a regular file? %s\n",
	    check_reg("input.txt") ? "yes" : "no");
	printf("docs is a directory? %s\n",
	    check_dir("docs") ? "yes" : "no");
	printf("/input.txt is a regular file? %s\n",
	    check_reg("/input.txt") ? "yes" : "no");
	printf("/docs is a directory? %s\n",
	    check_dir("/docs") ? "yes" : "no");
	return 0;
}


program CholeskyApp;

type
  D2Array = array of array of double;

function cholesky(const A: D2Array): D2Array;
var
  i, j, k: integer;
  s: double;
begin
  setlength(Result, length(A), length(A));
  for i := low(Result) to high(Result) do
    for j := 0 to i do
    begin
      s := 0;
      for k := 0 to j - 1 do
        s := s + Result[i][k] * Result[j][k];
      if i = j then
        Result[i][j] := sqrt(A[i][i] - s)
      else
        Result[i][j] := (A[i][j] - s) / Result[j][j];  // save one multiplication compared to the original
    end;
end;

procedure printM(const A: D2Array);
var
  i, j: integer;
begin
  for i := low(A) to high(A) do
  begin
    for j := low(A) to high(A) do
      write(A[i, j]: 8: 5);
    writeln;
  end;
end;

const
  m1: array[0..2, 0..2] of double = ((25, 15, -5), (15, 18, 0), (-5, 0, 11));
  m2: array[0..3, 0..3] of double = ((18, 22, 54, 42), (22, 70, 86, 62), (54, 86,
    174, 134), (42, 62, 134, 106));

var
  index, i: integer;
  cIn, cOut: D2Array;

begin
  setlength(cIn, length(m1), length(m1));
  for index := low(m1) to high(m1) do
  begin
    SetLength(cIn[index], length(m1[index]));
    for i := 0 to High(m1[Index]) do
      cIn[index][i] := m1[index][i];
  end;
  cOut := cholesky(cIn);
  printM(cOut);

  writeln;

  setlength(cIn, length(m2), length(m2));
  for index := low(m2) to high(m2) do
  begin
    SetLength(cIn[index], length(m2[Index]));
    for i := 0 to High(m2[Index]) do
      cIn[index][i] := m2[index][i];
  end;
  cOut := cholesky(cIn);
  printM(cOut);
end.


using System.IO;

Console.WriteLine(File.Exists("input.txt"));
Console.WriteLine(File.Exists("/input.txt"));
Console.WriteLine(Directory.Exists("docs"));
Console.WriteLine(Directory.Exists("/docs"));


#include "boost/filesystem.hpp"
#include <string>
#include <iostream>

void testfile(std::string name)
{
  boost::filesystem::path file(name);
  if (exists(file))
  {
    if (is_directory(file))
      std::cout << name << " is a directory.\n";
    else
      std::cout << name << " is a non-directory file.\n";
  }
  else
    std::cout << name << " does not exist.\n";
}

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


(dorun (map #(.exists (clojure.java.io/as-file %)) '("/input.txt" "/docs" "./input.txt" "./docs")))


       identification division.
       program-id. check-file-exist.

       environment division.
       configuration section.
       repository.
           function all intrinsic.

       data division.
       working-storage section.
       01 skip                 pic 9 value 2.
       01 file-name.
          05 value "/output.txt".
       01 dir-name.
          05 value "/docs/".
       01 unusual-name.
          05 value "Abdu'l-Bahá.txt".

       01 test-name            pic x(256).

       01 file-handle          usage binary-long.
       01 file-info.
          05 file-size         pic x(8) comp-x.
          05 file-date.
             10 file-day       pic x comp-x.
             10 file-month     pic x comp-x.
             10 file-year      pic xx comp-x.
          05 file-time.
             10 file-hours     pic x comp-x.
             10 file-minutes   pic x comp-x.
             10 file-seconds   pic x comp-x.
             10 file-hundredths  pic x comp-x.

       procedure division.
       files-main.

      *> check in current working dir
       move file-name(skip:) to test-name
       perform check-file

       move dir-name(skip:) to test-name
       perform check-file

       move unusual-name to test-name
       perform check-file

      *> check in root dir
       move 1 to skip
       move file-name(skip:) to test-name
       perform check-file

       move dir-name(skip:) to test-name
       perform check-file

       goback.

       check-file.
       call "CBL_CHECK_FILE_EXIST" using test-name file-info
       if return-code equal zero then
           display test-name(1:32) ": size " file-size ", "
                   file-year "-" file-month "-" file-day space
                   file-hours ":" file-minutes ":" file-seconds "."
                   file-hundredths
       else
           display "error: CBL_CHECK_FILE_EXIST " return-code space
                   trim(test-name)
       end-if
       .

       end program check-file-exist.


fs = require 'fs'
path = require 'path'

root = path.resolve '/'
current_dir = __dirname
filename = 'input.txt'
dirname = 'docs'

local_file = path.join current_dir, filename
local_dir = path.join current_dir, dirname

root_file = path.join root, filename
root_dir = path.join root, dirname

for p in [ local_file, local_dir, root_file, root_dir ] then do ( p ) ->
    fs.exists p, ( p_exists ) ->
        unless p_exists
            console.log "#{ p } does not exist."
        else then fs.stat p, ( error, stat ) ->
            console.log "#{ p } exists and is a #{ if stat.isFile() then 'file' else then 'directory' }."


with javascript_semantics
function cholesky(sequence matrix)
    integer l = length(matrix)
    sequence chol = repeat(repeat(0,l),l)
    for row=1 to l do
        for col=1 to row do
            atom x = matrix[row][col]
            for i=1 to col do
                x -= chol[row][i] * chol[col][i]
            end for
            chol[row][col] = iff(row == col ? sqrt(x) : x/chol[col][col])
        end for
    end for
    return chol
end function

ppOpt({pp_Nest,1})
pp(cholesky({{ 25, 15, -5 },
             { 15, 18,  0 },
             { -5,  0, 11 }}))
pp(cholesky({{ 18, 22,  54,  42},
             { 22, 70,  86,  62},
             { 54, 86, 174, 134},
             { 42, 62, 134, 106}}))


(if (probe-file (make-pathname :name "input.txt"))
    (print "rel file exists"))
(if (probe-file (make-pathname :directory '(:absolute "") :name "input.txt"))
    (print "abs file exists"))

(if (directory (make-pathname :directory '(:relative "docs")))
    (print "rel directory exists")
    (print "rel directory is not known to exist"))
(if (directory (make-pathname :directory '(:absolute "docs")))
    (print "abs directory exists")
    (print "abs directory is not known to exist"))


def check_file(filename : String)
  if File.directory?(filename)
    puts "#{filename} is a directory"
  elsif File.exists?(filename)
    puts "#{filename} is a file"
  else
    puts "#{filename} does not exist"
  end
end

check_file("input.txt")
check_file("docs")
check_file("/input.txt")
check_file("/docs")


import std.stdio, std.file, std.path;

void verify(in string name) {
    if (name.exists())
        writeln("'", name, "' exists");
    else
        writeln("'", name, "' doesn't exist");
}

void main() {
    // check in current working dir
    verify("input.txt");
    verify("docs");

    // check in root
    verify(dirSeparator ~ "input.txt");
    verify(dirSeparator ~ "docs");
}


(scl 9)
(load "@lib/math.l")

(de cholesky (A)
   (let L (mapcar '(() (need (length A) 0)) A)
      (for (I . R) A
         (for J I
            (let S (get R J)
               (for K (inc J)
                  (dec 'S (*/ (get L I K) (get L J K) 1.0)) )
               (set (nth L I J)
                  (if (= I J)
                     (sqrt S 1.0)
                     (*/ S 1.0 (get L J J)) ) ) ) ) )
      (for R L
         (for N R (prin (align 9 (round N 5))))
         (prinl) ) ) )


(subscriptrange):
decompose: procedure options (main);   /* 31 October 2013 */
   declare a(*,*) float controlled;

   allocate a(3,3) initial (25, 15, -5,
                            15, 18,  0,
                            -5,  0, 11);
    put skip list ('Original matrix:');
    put edit (a) (skip, 3 f(4));

    call cholesky(a);
    put skip list ('Decomposed matrix');
    put edit (a) (skip, 3 f(4));
    free a;
    allocate a(4,4) initial (18, 22,  54,  42,
                             22, 70,  86,  62,
                             54, 86, 174, 134,
                             42, 62, 134, 106);
    put skip list ('Original matrix:');
    put edit (a) (skip, (hbound(a,1)) f(12) );
    call cholesky(a);
    put skip list ('Decomposed matrix');
    put edit (a) (skip, (hbound(a,1)) f(12,5) );

cholesky: procedure(a);
   declare a(*,*) float;
   declare L(hbound(a,1), hbound(a,2)) float;
   declare s float;
   declare (i, j, k) fixed binary;

   L = 0;
   do i = lbound(a,1) to hbound(a,1);
      do j = lbound(a,2) to i;
         s = 0;
         do k = lbound(a,2) to j-1;
            s = s + L(i,k) * L(j,k);
         end;
         if i = j then
            L(i,j) = sqrt(a(i,i) - s);
         else
            L(i,j) = (a(i,j) - s) / L(j,j);
      end;
   end;
   a = L;
end cholesky;

end decompose;


;
;       Check file and directory exists for DBL version 4 by Dario B.
;
        PROC
;------------------------------------------------------------------
        XCALL FLAGS (0007000000,1)              ;Suppress STOP message

        CLOSE 1
        OPEN (1,O,'TT:')

        ;The file path can be written as:
        ;  "input.txt"                  (current directory)
        ;  "/directory/input.txt"       (complete path)
        ;  "DEV:input.txt"              (device DEV defined in shell)
        ;  "$DEV/input.txt"             (device DEV defined in shell)
        CLOSE 2
        OPEN (2,I,"input.txt")  [ERR=NOFIL]
        CLOSE 2

        ;Check directory (unix/linux systems)
        CLOSE 2
        OPEN (2,O,"/docs/.")    [ERR=NODIR]

        GOTO CLOS

;--------------------------------------------------------
NOFIL,  DISPLAY (1,"File input.txt not found!",10)
        GOTO CLOS

NODIR,  DISPLAY (1,"Directory /docs not found!",10)
        GOTO CLOS

CLOS,   CLOSE 1
        CLOSE 2
        STOP


$ if f$search( "input.txt" ) .eqs. ""
$ then
$  write sys$output "input.txt not found"
$ else
$  write sys$output "input.txt found"
$ endif
$ if f$search( "docs.dir" ) .eqs. ""
$ then
$  write sys$output "directory docs not found"
$ else
$  write sys$output "directory docs found"
$ endif
$ if f$search( "[000000]input.txt" ) .eqs. ""
$ then
$  write sys$output "[000000]input.txt not found"
$ else
$  write sys$output "[000000]input.txt found"
$ endif
$ if f$search( "[000000]docs.dir" ) .eqs. ""
$ then
$  write sys$output "directory [000000]docs not found"
$ else
$  write sys$output "directory [000000]docs found"
$ endif


program EnsureFileExists;

{$APPTYPE CONSOLE}

uses
  SysUtils;

begin
  if FileExists('input.txt') then
    Writeln('File "input.txt" exists.')
  else
    Writeln('File "input.txt" does not exist.');

  if FileExists('\input.txt') then
    Writeln('File "\input.txt" exists.')
  else
    Writeln('File "\input.txt" does not exist.');

  if DirectoryExists('docs') then
    Writeln('Directory "docs" exists.')
  else
    Writeln('Directory "docs" does not exists.');

  if DirectoryExists('\docs') then
    Writeln('Directory "\docs" exists.')
  else
    Writeln('Directory "\docs" does not exists.');
end.


from __future__ import print_function

from pprint import pprint
from math import sqrt

def cholesky(A):
    L = [[0.0] * len(A) for _ in xrange(len(A))]
    for i in xrange(len(A)):
        for j in xrange(i+1):
            s = sum(L[i][k] * L[j][k] for k in xrange(j))
            L[i][j] = sqrt(A[i][i] - s) if (i == j) else \
                      (1.0 / L[j][j] * (A[i][j] - s))
    return L

if __name__ == "__main__":
    m1 = [[25, 15, -5],
          [15, 18,  0],
          [-5,  0, 11]]
    pprint(cholesky(m1))
    print()

    m2 = [[18, 22,  54,  42],
          [22, 70,  86,  62],
          [54, 86, 174, 134],
          [42, 62, 134, 106]]
    pprint(cholesky(m2), width=120)


for file in [<file:input.txt>,
             <file:///input.txt>] {
  require(file.exists(),       fn { `$file is missing!` })
  require(!file.isDirectory(), fn { `$file is a directory!` })
}

for file in [<file:docs>,
             <file:///docs>] {
  require(file.exists(),      fn { `$file is missing!` })
  require(file.isDirectory(), fn { `$file is not a directory!` })
}


import system'io;
import extensions;

extension op
{
    validatePath()
        = self.Available.iif("exists","not found");
}

public program()
{
    console.printLine("input.txt file ",File.assign("input.txt").validatePath());

    console.printLine("\input.txt file ",File.assign("\input.txt").validatePath());

    console.printLine("docs directory ",Directory.assign("docs").validatePath());

    console.printLine("\docs directory ",Directory.assign("\docs").validatePath())
}


File.regular?("input.txt")
File.dir?("docs")
File.regular?("/input.txt")
File.dir?("/docs")


solve:{[A;B] $[0h>type A;B%A;inv[A] mmu B]}
ak:{[m;k] (),/:m[;k]til k:k-1}
akk:{[m;k] m[k;k:k-1]}
transpose:{$[0h=type x;flip x;enlist each x]}
mult:{[A;B]$[0h=type A;A mmu B;A*B]}
cholesky:{[A]
	{[A;L;n]
		l_k:solve[L;ak[A;n]];
		l_kk:first over sqrt[akk[A;n] - mult[transpose l_k;l_k]];
		({$[0h<type x;enlist x;x]}L,'0f),enlist raze transpose[l_k],l_kk
		}[A]/[sqrt A[0;0];1_1+til count first A]
	}

show cholesky (25 15 -5f;15 18 0f;-5 0 11f)
-1"";
show cholesky (18 22 54 42f;22 70 86 62f;54 86 174 134f;42 62 134 106f)


(file-exists-p "input.txt")
(file-directory-p "docs")
(file-exists-p "/input.txt")
(file-directory-p "/docs")


#!/usr/bin/escript
existence( true ) ->"exists";
existence( false ) ->"does not exist".

print_result(Type, Name, Flag) -> io:fwrite( "~s ~s ~s~n", [Type, Name, existence(Flag)] ).

main(_) ->
        print_result( "File", "input.txt", filelib:is_regular("input.txt") ),
        print_result( "Directory", "docs", filelib:is_dir("docs") ),
        print_result( "File", "/input.txt", filelib:is_regular("/input.txt") ),
        print_result( "Directory", "/docs", filelib:is_dir("/docs") ).


include file.e

procedure ensure_exists(sequence name)
    object x
    sequence s
    x = dir(name)
    if sequence(x) then
        if find('d',x[1][D_ATTRIBUTES]) then
            s = "directory"
        else
            s = "file"
        end if
        printf(1,"%s %s exists.\n",{name,s})
    else
        printf(1,"%s does not exist.\n",{name})
    end if
end procedure

ensure_exists("input.txt")
ensure_exists("docs")
ensure_exists("/input.txt")
ensure_exists("/docs")


#lang racket
(require math)

(define (cholesky A)
  (define mref matrix-ref)
  (define n (matrix-num-rows A))
  (define L (for/vector ([_ n]) (for/vector ([_ n]) 0)))
  (define (set L i j x) (vector-set! (vector-ref L i) j x))
  (define (ref L i j) (vector-ref (vector-ref L i) j))
  (for* ([i n] [k n])
    (set L i k
         (cond
           [(= i k)
            (sqrt (- (mref A i i) (for/sum ([j k]) (sqr (ref L k j)))))]
           [(> i k)
            (/ (- (mref A i k) (for/sum ([j k]) (* (ref L i j) (ref L k j))))
               (ref L k k))]
           [else 0])))
  L)

(cholesky (matrix [[25 15 -5]
                   [15 18  0]
                   [-5  0 11]]))

(cholesky (matrix [[18 22  54 42]
                   [22 70  86 62]
                   [54 86 174 134]
                   [42 62 134 106]]))


open System.IO
File.Exists("input.txt")
Directory.Exists("docs")
File.Exists("/input.txt")
Directory.Exists(@"\docs")


: print-exists? ( path -- )
    [ write ": " write ] [ exists? "exists." "doesn't exist." ? print ] bi ;

{ "input.txt" "/input.txt" "docs" "/docs" } [ print-exists? ] each


: .exists ( str len -- ) 2dup file-status nip 0= if ."  exists" else ."  does not exist" then type ;
 s" input.txt" .exists
s" /input.txt" .exists
 s" docs" .exists
s" /docs" .exists


LOGICAL :: file_exists
INQUIRE(FILE="input.txt", EXIST=file_exists)   ! file_exists will be TRUE if the file
                                               ! exists and FALSE otherwise
INQUIRE(FILE="/input.txt", EXIST=file_exists)


/*REXX program performs the Cholesky decomposition on a square matrix & displays results*/
niner =  '25  15  -5' ,                          /*define a  3x3  matrix with elements. */
         '15  18   0' ,
         '-5   0  11'
                           call Cholesky niner
hexer =  18  22  54  42,                         /*define a  4x4  matrix with elements. */
         22  70  86  62,
         54  86 174 134,
         42  62 134 106
                           call Cholesky hexer
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Cholesky: procedure;  parse arg mat;   say;   say;   call tell 'input array',mat
              do    r=1  for ord
                 do c=1  for r; $=0;  do i=1  for c-1;  $= $  +  !.r.i * !.c.i;  end /*i*/
                 if r=c  then !.r.r= sqrt(!.r.r - $)
                         else !.r.c= 1 / !.c.c * (@.r.c - $)
                 end   /*c*/
              end      /*r*/
          call tell  'Cholesky factor',,!.,'─'
          return
/*──────────────────────────────────────────────────────────────────────────────────────*/
err:   say;   say;   say '***error***!';      say;    say arg(1);   say;   say;    exit 13
/*──────────────────────────────────────────────────────────────────────────────────────*/
tell:  parse arg hdr,x,y,sep;   #=0;          if sep==''  then sep= '═'
       dPlaces= 5                                /*# dec. places past the decimal point.*/
       width  =10                                /*field width used to display elements.*/
       if y==''  then !.=0
                 else do row=1  for ord;  do col=1  for ord;  x=x !.row.col;  end;   end
       w=words(x)
               do ord=1  until ord**2>=w;  end   /*a fast way to find the matrix's order*/
       say
       if ord**2\==w  then call err  "matrix elements don't form a square matrix."
       say center(hdr, ((width + 1) * w) % ord,  sep)
       say
               do   row=1  for ord;         z=
                 do col=1  for ord;         #= # + 1
                                    @.row.col= word(x, #)
                 if col<=row  then  !.row.col= @.row.col
                 z=z  right( format(@.row.col, , dPlaces) / 1,   width)
                 end   /*col*/                   /*       ↑↑↑                           */
               say z                             /*       └┴┴──◄──normalization for zero*/
               end        /*row*/
       return
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt:  procedure; parse arg x;  if x=0  then return 0;  d=digits(); numeric digits;  h=d+6
       numeric form; m.=9; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_ %2
         do j=0  while h>9;      m.j=h;              h=h%2+1;       end  /*j*/
         do k=j+5  to 0  by -1;  numeric digits m.k; g=(g+x/g)*.5;  end  /*k*/; return g/1


' FB 1.05.0 Win64

' Enable FileExists() function to be used
#include "file.bi"

' Use Win32 function to check if directory exists on Windows 10
Declare Function GetFileAttributes Lib "kernel32.dll" Alias "GetFileAttributesA" _
(ByVal lpFileName As ZString Ptr) As ULong

Const InvalidFileAttributes As ULong = -1UL
Const FileAttributeDirectory As ULong = &H10UL

Sub CheckFileExists(ByRef filePath As String)
  If FileExists(filePath) Then
    Print "'"; filePath; "' exists"
  Else
    Print "'"; filePath; "' does not exist"
  End If
End Sub

Sub CheckDirectoryExists(ByVal dirPath As ZString Ptr)
  Dim attrib As ULong = GetFileAttributes(dirPath)
  Dim dirExists As ULong = attrib <> InvalidFileAttributes AndAlso (attrib And FileAttributeDirectory) <> 0
  If dirExists Then
    Print "'"; *dirPath; "' exists"
  Else
    Print "'"; *dirPath; "' does not exist"
  End If
End Sub

CheckFileExists(CurDir + "\input.txt")
Dim dirPath As String = CurDir + "\docs"
CheckDirectoryExists(StrPtr(dirPath))
CheckFileExists("c:\input.txt")
CheckDirectoryExists(StrPtr("c:\docs"))
Print
Print "Press any key to quit the program"
Sleep


checkFile[filename] :=
{
   file = newJava["java.io.File", [filename]]
   if file.exists[] and file.isFile[]
      println["$filename is a file"]
   else
      println["$filename is not a file"]
}

checkDir[filename] :=
{
   file = newJava["java.io.File", [filename]]
   if file.exists[] and file.isDirectory[]
      println["$filename is a directory"]
   else
      println["$filename is not a directory"]
}

checkFile["input.txt"]
checkFile["/input.txt"]
checkDir["docs"]
checkDir["/docs"]

// This tests the "unusual" filename with various Unicode
// normalizations that would look identical to a human
// For example, the á character could be written as either
// the Unicode sequences
//    \u00e1   ('LATIN SMALL LETTER A WITH ACUTE')
// or
//    \u0061\u0301  ('LATIN SMALL LETTER A' 'COMBINING ACUTE ACCENT')
unusual = "`Abdu'l-Bahá.txt"
checkFile[unusual]
checkFile[normalizeUnicode[unusual, "NFC"]]
checkFile[normalizeUnicode[unusual, "NFD"]]


Public Sub Main()

If Exist(User.Home &/ "input.txt") Then Print "'input.txt' does exist in the Home folder"
If Not Exist("/input.txt") Then Print "'input.txt' does NOT exist in Root"                'Not messing With my Root files

If Exist(User.home &/ "docs/") Then Print "The folder '~/docs' does exist"
If Not Exist("/docs/") Then Print "The folder '/docs' does NOT exist"                     'Not messing With my Root files

File.Save(User.Home &/ "`Abdu'l-Bahá.txt", "")
If Exist(User.Home &/ "`Abdu'l-Bahá.txt") Then Print "'`Abdu'l-Bahá.txt' does exist (zero length and unusual name)"

End


# Project : Cholesky decomposition

load "stdlib.ring"
decimals(5)
m1 = [[25, 15, -5],
          [15, 18,  0],
          [-5,  0, 11]]
cholesky(m1)
printarray(m1)
see nl

m2 = [[18, 22,  54,  42],
          [22, 70,  86,  62],
          [54, 86, 174, 134],
          [42, 62, 134, 106]]
cholesky(m2)
printarray(m2)

func cholesky(a)
l = newlist(len(a), len(a))
for i = 1 to len(a)
     for j = 1 to i
         s = 0
         for k = 1 to j
             s = s + l[i][k] * l[j][k]
         next
         if i = j
            l[i][j] = sqrt(a[i][i] - s)
         else
            l[i][j] = (a[i][j] - s) / l[j][j]
         ok
    next
next
a = l

func printarray(a)
       for row = 1 to len(a)
            for col = 1 to len(a)
                 see "" + a[row][col] + "  "
            next
            see nl
       next


require 'matrix'

class Matrix
  def symmetric?
    return false if not square?
    (0 ... row_size).each do |i|
      (0 .. i).each do |j|
        return false if self[i,j] != self[j,i]
      end
    end
    true
  end

  def cholesky_factor
    raise ArgumentError, "must provide symmetric matrix" unless symmetric?
    l = Array.new(row_size) {Array.new(row_size, 0)}
    (0 ... row_size).each do |k|
      (0 ... row_size).each do |i|
        if i == k
          sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[k][j] ** 2}
          val = Math.sqrt(self[k,k] - sum)
          l[k][k] = val
        elsif i > k
          sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[i][j] * l[k][j]}
          val = (self[k,i] - sum) / l[k][k]
          l[i][k] = val
        end
      end
    end
    Matrix[*l]
  end
end

puts Matrix[[25,15,-5],[15,18,0],[-5,0,11]].cholesky_factor
puts Matrix[[18, 22,  54,  42],
            [22, 70,  86,  62],
            [54, 86, 174, 134],
            [42, 62, 134, 106]].cholesky_factor


IsExistingFile("input.txt");
IsDirectoryPath("docs");
IsExistingFile("/input.txt");
IsDirectoryPath("/docs");


[indent=4]
/*
   Check file exists, in Genie
   valac --pkg=gio-2.0 checkFile.gs
*/

init
    Intl.setlocale()

    files:array of string[] = {"input.txt", "docs",
    Path.DIR_SEPARATOR_S + "input.txt", Path.DIR_SEPARATOR_S + "docs", "`Abdu'l-Bahá.txt"}
    for f:string in files
        var file = File.new_for_path(f)
        var exists = file.query_exists()
        var dir = false
        if exists
            dir = file.query_file_type(0) == FileType.DIRECTORY
        print("%s %sexist%s%s", f, exists ? "" : "does not ", exists ? "s" : "", dir ? " and is a directory" : "")


package main

import (
    "fmt"
    "os"
)

func printStat(p string) {
    switch i, err := os.Stat(p); {
    case err != nil:
        fmt.Println(err)
    case i.IsDir():
        fmt.Println(p, "is a directory")
    default:
        fmt.Println(p, "is a file")
    }
}

func main() {
    printStat("input.txt")
    printStat("/input.txt")
    printStat("docs")
    printStat("/docs")
}


fn cholesky(mat: Vec<f64>, n: usize) -> Vec<f64> {
    let mut res = vec![0.0; mat.len()];
    for i in 0..n {
        for j in 0..(i+1){
            let mut s = 0.0;
            for k in 0..j {
                s += res[i * n + k] * res[j * n + k];
            }
            res[i * n + j] = if i == j { (mat[i * n + i] - s).sqrt() } else { (1.0 / res[j * n + j] * (mat[i * n + j] - s)) };
        }
    }
    res
}

fn show_matrix(matrix: Vec<f64>, n: usize){
    for i in 0..n {
        for j in 0..n {
            print!("{:.4}\t", matrix[i * n + j]);
        }
        println!("");
    }
    println!("");
}

fn main(){
    let dimension = 3 as usize;
    let m1 = vec![25.0, 15.0, -5.0,
                  15.0, 18.0,  0.0,
                  -5.0,  0.0, 11.0];
    let res1 = cholesky(m1, dimension);
    show_matrix(res1, dimension);

    let dimension = 4 as usize;
    let m2 = vec![18.0, 22.0,  54.0,  42.0,
                  22.0, 70.0,  86.0,  62.0,
                  54.0, 86.0, 174.0, 134.0,
                  42.0, 62.0, 134.0, 106.0];
    let res2 = cholesky(m2, dimension);
    show_matrix(res2, dimension);
}


case class Matrix( val matrix:Array[Array[Double]] ) {

  // Assuming matrix is positive-definite, symmetric and not empty...

  val rows,cols = matrix.size

  def getOption( r:Int, c:Int ) : Option[Double] = Pair(r,c) match {
    case (r,c) if r < rows && c < rows => Some(matrix(r)(c))
    case _ => None
  }

  def isLowerTriangle( r:Int, c:Int ) : Boolean = { c <= r }
  def isDiagonal( r:Int, c:Int ) : Boolean = { r == c}

  override def toString = matrix.map(_.mkString(", ")).mkString("\n")

  /**
   * Perform Cholesky Decomposition of this matrix
   */
  lazy val cholesky : Matrix = {

    val l = Array.ofDim[Double](rows*cols)

    for( i <- (0 until rows); j <- (0 until cols) ) yield {

      val s = (for( k <- (0 until j) ) yield { l(i*rows+k) * l(j*rows+k) }).sum

      l(i*rows+j) = (i,j) match {
        case (r,c) if isDiagonal(r,c) => scala.math.sqrt(matrix(i)(i) - s)
        case (r,c) if isLowerTriangle(r,c) => (1.0 / l(j*rows+j) * (matrix(i)(j) - s))
        case _ => 0
      }
    }

    val m = Array.ofDim[Double](rows,cols)
    for( i <- (0 until rows); j <- (0 until cols) ) m(i)(j) = l(i*rows+j)
    Matrix(m)
  }
}

// A little test...
val a1 = Matrix(Array[Array[Double]](Array(25,15,-5),Array(15,18,0),Array(-5,0,11)))
val a2 = Matrix(Array[Array[Double]](Array(18,22,54,42), Array(22,70,86,62), Array(54,86,174,134), Array(42,62,134,106)))

val l1 = a1.cholesky
val l2 = a2.cholesky

// Given test results
val r1 = Array[Double](5,0,0,3,3,0,-1,1,3)
val r2 = Array[Double](4.24264,0.00000,0.00000,0.00000,5.18545,6.56591,0.00000,0.00000,
                        12.72792,3.04604,1.64974,0.00000,9.89949,1.62455,1.84971,1.39262)

// Verify assertions
(l1.matrix.flatten.zip(r1)).foreach{ case (result,test) =>
  assert(math.round( result * 100000 ) * 0.00001 == math.round( test * 100000 ) * 0.00001)
}

(l2.matrix.flatten.zip(r2)).foreach{ case (result,test) =>
  assert(math.round( result * 100000 ) * 0.00001 == math.round( test * 100000 ) * 0.00001)
}


println new File('input.txt').exists()
println new File('/input.txt').exists()
println new File('docs').exists()
println new File('/docs').exists()


import System.Directory (doesFileExist, doesDirectoryExist)

check :: (FilePath -> IO Bool) -> FilePath -> IO ()
check p s = do
  result <- p s
  putStrLn $
    s ++
    if result
      then " does exist"
      else " does not exist"

main :: IO ()
main = do
  check doesFileExist "input.txt"
  check doesDirectoryExist "docs"
  check doesFileExist "/input.txt"
  check doesDirectoryExist "/docs"


println "File \"input.txt\"? " + (exists "input.txt")
println "Dir \"docs\"?       " + (exists "docs/")
println "File \"/input.txt\"? " + (exists "/input.txt")
println "Dir \"/docs\"?       " + (exists "/docs/")


$ include "seed7_05.s7i";
  include "float.s7i";
  include "math.s7i";

const type: matrix is array array float;

const func matrix: cholesky (in matrix: a) is func
  result
    var matrix: cholesky is 0 times 0 times 0.0;
  local
    var integer: i is 0;
    var integer: j is 0;
    var integer: k is 0;
    var float: sum is 0.0;
  begin
    cholesky := length(a) times length(a) times 0.0;
    for key i range cholesky do
      for j range 1 to i do
	sum := 0.0;
	for k range 1 to j do
	  sum +:= cholesky[i][k] * cholesky[j][k];
        end for;
	if i = j then
	  cholesky[i][i] := sqrt(a[i][i] - sum)
	else
          cholesky[i][j] := (a[i][j] - sum) / cholesky[j][j];
        end if;
      end for;
    end for;
  end func;

const proc: writeMat (in matrix: a) is func
  local
    var integer: i is 0;
    var float: num is 0.0;
  begin
    for key i range a do
      for num range a[i] do
        write(num digits 5 lpad 8);
      end for;
      writeln;
    end for;
  end func;

const matrix: m1 is [] (
    [] (25.0, 15.0, -5.0),
    [] (15.0, 18.0,  0.0),
    [] (-5.0,  0.0, 11.0));
const matrix: m2 is [] (
    [] (18.0, 22.0,  54.0,  42.0),
    [] (22.0, 70.0,  86.0,  62.0),
    [] (54.0, 86.0, 174.0, 134.0),
    [] (42.0, 62.0, 134.0, 106.0));

const proc: main is func
  begin
    writeMat(cholesky(m1));
    writeln;
    writeMat(cholesky(m2));
  end func;


   OPEN(FIle=   'input.txt', OLD, IOStat=ios, ERror=99)
   OPEN(FIle='C:\input.txt', OLD, IOStat=ios, ERror=99)
! ...
99 WRITE(Messagebox='!') 'File does not exist. Error message ', ios


U0 FileExists(U8 *f) {
  if (FileFind(f) && !IsDir(f)) {
    Print("'%s' file exists.\n", f);
  } else {
    Print("'%s' file does not exist.\n", f);
  }
}

U0 DirExists(U8 *d) {
  if (IsDir(d)) {
    Print("'%s' directory exists.\n", d);
  } else {
    Print("'%s' directory does not exist.\n", d);
  }
}

FileExists("input.txt");
FileExists("::/input.txt");
DirExists("docs");
DirExists("::/docs");


concept exists(path) {
	open(path)
	errors {
		if error.DoesNotExist()
			print(path, " does not exist!")
		end
		return
	}
	print(path, " exists!")
}

software {
	exists("input.txt")
	exists("/input.txt")
	exists("docs")
	exists("/docs")
	exists("docs/Abdu'l-Bahá.txt")
}


every dir := !["./","/"] do {
   write("file ", f := dir || "input.txt", if stat(f) then " exists." else " doesn't exist.")
   write("directory ", f := dir || "docs", if stat(f) then " exists." else " doesn't exist.")
   }


func cholesky(matrix) {
    var chol = matrix.len.of { matrix.len.of(0) }
    for row in ^matrix {
        for col in (0..row) {
            var x = matrix[row][col]
            for i in (0..col) {
                x -= (chol[row][i] * chol[col][i])
            }
            chol[row][col] = (row == col ? x.sqrt : x/chol[col][col])
        }
    }
    return chol
}


FloatMatrix>>#cholesky
	| l |
	l := FloatMatrix zero: numRows.
	1 to: numRows do: [:i |
		1 to: i do: [:k | | rowSum lkk factor aki partialSum |
			i = k
				ifTrue: [
					rowSum := (1 to: k - 1) sum: [:j | | lkj |
						lkj := l at: j @ k.
						lkj squared].
					lkk := (self at: k @ k) - rowSum.
					lkk := lkk sqrt.
					l at: k @ k put: lkk]
				ifFalse: [
					factor := l at: k @ k.
					aki := self at: k @ i.
					partialSum := (1 to: k - 1) sum: [:j | | ljk lji |
						lji := l at: j @ i.
						ljk := l at: j @ k.
						lji * ljk].
					l at: k @ i put: aki - partialSum * factor reciprocal]]].
	^l


print, FILE_TEST('input.txt')
print, FILE_TEST(PATH_SEP()+'input.txt')
print, FILE_TEST('docs', /DIRECTORY)
print, FILE_TEST(PATH_SEP()+'docs', /DIRECTORY)


require 'files'
fexist 'input.txt'
fexist '/input.txt'
direxist=: 2 = ftype
direxist 'docs'
direxist '/docs'


import java.io.File;
public class FileExistsTest {
   public static boolean isFileExists(String filename) {
       boolean exists = new File(filename).exists();
       return exists;
   }
   public static void test(String type, String filename) {
       System.out.println("The following " + type + " called " + filename +
           (isFileExists(filename) ? " exists." : " not exists.")
       );
   }
   public static void main(String args[]) {
        test("file", "input.txt");
        test("file", File.separator + "input.txt");
        test("directory", "docs");
        test("directory", File.separator + "docs" + File.separator);
   }
}


func cholesky(matrix: [Double], n: Int) -> [Double] {
  var res = [Double](repeating: 0, count: matrix.count)

  for i in 0..<n {
    for j in 0..<i+1 {
      var s = 0.0

      for k in 0..<j {
        s += res[i * n + k] * res[j * n + k]
      }

      if i == j {
        res[i * n + j] = (matrix[i * n + i] - s).squareRoot()
      } else {
        res[i * n + j] = (1.0 / res[j * n + j] * (matrix[i * n + j] - s))
      }
    }
  }

  return res
}

func printMatrix(_ matrix: [Double], n: Int) {
  for i in 0..<n {
    for j in 0..<n {
      print(matrix[i * n + j], terminator: " ")
    }

    print()
  }
}

let res1 = cholesky(
  matrix: [25.0, 15.0, -5.0,
           15.0, 18.0,  0.0,
           -5.0,  0.0, 11.0],
  n: 3
)

let res2 = cholesky(
  matrix: [18.0, 22.0,  54.0,  42.0,
           22.0, 70.0,  86.0,  62.0,
           54.0, 86.0, 174.0, 134.0,
           42.0, 62.0, 134.0, 106.0],
  n: 4
)

printMatrix(res1, n: 3)
print()
printMatrix(res2, n: 4)


proc cholesky a {
    set m [llength $a]
    set n [llength [lindex $a 0]]
    set l [lrepeat $m [lrepeat $n 0.0]]
    for {set i 0} {$i < $m} {incr i} {
	for {set k 0} {$k < $i+1} {incr k} {
	    set sum 0.0
	    for {set j 0} {$j < $k} {incr j} {
		set sum [expr {$sum + [lindex $l $i $j] * [lindex $l $k $j]}]
	    }
	    lset l $i $k [expr {
		$i == $k
		? sqrt([lindex $a $i $i] - $sum)
		: (1.0 / [lindex $l $k $k] * ([lindex $a $i $k] - $sum))
	    }]
	}
    }
    return $l
}


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

fso.FileExists('input.txt');
fso.FileExists('c:/input.txt');
fso.FolderExists('docs');
fso.FolderExists('c:/docs');


@show isfile("input.txt")
@show isfile("/input.txt")
@show isdir("docs")
@show isdir("/docs")
@show isfile("")
@show isfile("`Abdu'l-Bahá.txt")


include ..\Utilitys.tlhy

"foo.bar" "w" fopen
"Hallo !" over fputs
fclose

"fou.bar" "r" fopen
dup 0 < ( ["Could not open 'fou.bar' for reading" print drop] [fclose] ) if

" " input


// version 1.0.6

import java.io.File

fun main(args: Array<String>) {
    val filePaths = arrayOf("input.txt", "c:\\input.txt", "zero_length.txt", "`Abdu'l-Bahá.txt")
    val dirPaths  = arrayOf("docs", "c:\\docs")
    for (filePath in filePaths) {
        val f = File(filePath)
        println("$filePath ${if (f.exists() && !f.isDirectory) "exists" else "does not exist"}")
    }
    for (dirPath in dirPaths) {
        val d = File(dirPath)
        println("$dirPath ${if (d.exists() && d.isDirectory) "exists" else "does not exist"}")
    }
}


Function Cholesky(Mat As Range) As Variant

Dim A() As Double, L() As Double, sum As Double, sum2 As Double
Dim m As Byte, i As Byte, j As Byte, k As Byte

'Ensure matrix is square
    If Mat.Rows.Count <> Mat.Columns.Count Then
        MsgBox ("Correlation matrix is not square")
        Exit Function
    End If

    m = Mat.Rows.Count

'Initialize and populate matrix A of values and matrix L which will be the lower Cholesky
    ReDim A(0 To m - 1, 0 To m - 1)
    ReDim L(0 To m - 1, 0 To m - 1)
    For i = 0 To m - 1
        For j = 0 To m - 1
            A(i, j) = Mat(i + 1, j + 1).Value2
            L(i, j) = 0
        Next j
    Next i

'Handle the simple cases explicitly to save time
    Select Case m
        Case Is = 1
            L(0, 0) = Sqr(A(0, 0))

        Case Is = 2
            L(0, 0) = Sqr(A(0, 0))
            L(1, 0) = A(1, 0) / L(0, 0)
            L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0))

        Case Else
            L(0, 0) = Sqr(A(0, 0))
            L(1, 0) = A(1, 0) / L(0, 0)
            L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0))
            For i = 2 To m - 1
                sum2 = 0
                For k = 0 To i - 1
                    sum = 0
                    For j = 0 To k
                        sum = sum + L(i, j) * L(k, j)
                    Next j
                    L(i, k) = (A(i, k) - sum) / L(k, k)
                    sum2 = sum2 + L(i, k) * L(i, k)
                Next k
                L(i, i) = Sqr(A(i, i) - sum2)
            Next i
    End Select
    Cholesky = L
End Function


import math

// Symmetric and Lower use a packed representation that stores only
// the Lower triangle.

struct Symmetric {
    order int
    ele   []f64
}

struct Lower  {
mut:
    order int
    ele   []f64
}

// Symmetric.print prints a square matrix from the packed representation,
// printing the upper triange as a transpose of the Lower.
fn (s Symmetric) print() {
    mut row, mut diag := 1, 0
    for i, e in s.ele {
        print("${e:10.5f} ")
        if i == diag {
            for j, col := diag+row, row; col < s.order; j += col {
                print("${s.ele[j]:10.5f} ")
                col++
            }
            println('')
            row++
            diag += row
        }
    }
}

// Lower.print prints a square matrix from the packed representation,
// printing the upper triangle as all zeros.
fn (l Lower) print() {
    mut row, mut diag := 1, 0
    for i, e in l.ele {
        print("${e:10.5f} ")
        if i == diag {
            for _ in row..l.order {
                print("${0.0:10.5f} ")
            }
            println('')
            row++
            diag += row
        }
    }
}

// cholesky_lower returns the cholesky decomposition of a Symmetric real
// matrix.  The matrix must be positive definite but this is not checked.
fn (a Symmetric) cholesky_lower() Lower {
    mut l := Lower{a.order, []f64{len: a.ele.len}}
    mut row, mut col := 1, 1
    mut dr := 0 // index of diagonal element at end of row
    mut dc := 0 // index of diagonal element at top of column
    for i, e in a.ele {
        if i < dr {
            d := (e - l.ele[i]) / l.ele[dc]
            l.ele[i] = d
            mut ci, mut cx := col, dc
            for j := i + 1; j <= dr; j++ {
                cx += ci
                ci++
                l.ele[j] += d * l.ele[cx]
            }
            col++
            dc += col
        } else {
            l.ele[i] = math.sqrt(e - l.ele[i])
            row++
            dr += row
            col = 1
            dc = 0
        }
    }
    return l
}

fn main() {
    demo(Symmetric{3, [
        f64(25),
        15, 18,
        -5, 0, 11]})
    demo(Symmetric{4, [
        f64(18),
        22, 70,
        54, 86, 174,
        42, 62, 134, 106]})
}

fn demo(a Symmetric) {
    println("A:")
    a.print()
    println("L:")
    a.cholesky_lower().print()
}


// local file
file_exists('input.txt')

// local directory
file_exists('docs')

// file in root file system (requires permissions at user OS level)
file_exists('//input.txt')

// directory in root file system (requires permissions at user OS level)
file_exists('//docs')


> (: filelib is_regular '"input.txt")
false
> (: filelib is_dir '"docs")
false
> (: filelib is_regular '"/input.txt")
false
> (: filelib is_dir '"/docs"))
false


'fileExists.bas - Show how to determine if a file exists
dim info$(10,10)
input "Type a file path (ie. c:\windows\somefile.txt)?"; fpath$
if fileExists(fpath$) then
    print fpath$; " exists!"
else
    print fpath$; " doesn't exist!"
end if
end

'return a true if the file in fullPath$ exists, else return false
function fileExists(fullPath$)
    files pathOnly$(fullPath$), filenameOnly$(fullPath$), info$()
    fileExists = val(info$(0, 0)) > 0
end function

'return just the directory path from a full file path
function pathOnly$(fullPath$)
    pathOnly$ = fullPath$
    while right$(pathOnly$, 1) <> "\" and pathOnly$ <> ""
        pathOnly$ = left$(pathOnly$, len(pathOnly$)-1)
    wend
end function

'return just the filename from a full file path
function filenameOnly$(fullPath$)
    pathLength = len(pathOnly$(fullPath$))
    filenameOnly$ = right$(fullPath$, len(fullPath$)-pathLength)
end function


import "/matrix" for Matrix
import "/fmt" for Fmt

var arrays = [
    [ [25, 15, -5],
      [15, 18,  0],
      [-5,  0, 11] ],

    [ [18, 22,  54,  42],
      [22, 70,  86,  62],
      [54, 86, 174, 134],
      [42, 62, 134, 106] ]
]

for (array in arrays) {
    System.print("Original:")
    Fmt.mprint(array, 3, 0)
    System.print("\nLower Cholesky factor:")
    Fmt.mprint(Matrix.new(array).cholesky(), 8, 5)
    System.print()
}


var [const] GSL=Import("zklGSL");	// libGSL (GNU Scientific Library)
fcn lowerCholesky(m){  // trans: C
   rows:=m.rows;
   lcm:=GSL.Matrix(rows,rows);	// zero filled
   foreach i,j in (rows,i+1){
      s:=(0).reduce(j,'wrap(s,k){ s + lcm[i,k]*lcm[j,k] },0.0);
      lcm[i,j]=( if(i==j)(m[i,i] - s).sqrt()
	         else     1.0/lcm[j,j]*(m[i,j] - s) );
   }
   lcm
}


if (exists("input.txt")) {
    puts("The file \"input.txt\" exist");
}
if (exists("/input.txt")) {
    puts("The file \"/input.txt\" exist");
}
if (exists("docs")) {
    puts("The file \"docs\" exist");
}
if (exists("/docs")) {
    puts("The file \"/docs\" exist");
}


there is a file "/input.txt"
there is a file "input.txt"
there is a folder "docs"
there is a file "/docs/input.txt"


show file? "input.txt
show file? "/input.txt
show file? "docs
show file? "/docs


function output( s, b )
    if b then
        print ( s, " does not exist." )
    else
        print ( s, " does exist." )
    end
end

output( "input.txt",  io.open( "input.txt", "r" ) == nil )
output( "/input.txt", io.open( "/input.txt", "r" ) == nil )
output( "docs",  io.open( "docs", "r" ) == nil )
output( "/docs", io.open( "/docs", "r" ) == nil )


Module ExistDirAndFile {
      Let WorkingDir$=Dir$, RootDir$="C:\"

      task(WorkingDir$)
      task(RootDir$)
      Dir User ' return to user directroy

      Sub task(WorkingDir$)
            Local counter
            Dir WorkingDir$
            If Not Exist.Dir("docs") then Report  "docs not exist in "+WorkingDir$ : counter++
            If Not Exist("output.txt") Then {
                  Report "output.txt not exist in "+ WorkingDir$ : counter++
            } Else.if Filelen("output.txt")=0 Then Report "output.txt has zero length"
            If counter =0 then Report  WorkingDir$+ " has docs directory and file output.txt"
      End Sub
}
ExistDirAndFile


with(FileTools):
Exists("input.txt");
Exists("docs") and IsDirectory("docs");
Exists("/input.txt");
Exists("/docs") and IsDirectory("/docs");


wd = NotebookDirectory[];
FileExistsQ[wd <> "input.txt"]
DirectoryQ[wd <> "docs"]

FileExistsQ["/" <> "input.txt"]
DirectoryQ["/" <> "docs"]


 exist('input.txt','file')
 exist('/input.txt','file')
 exist('docs','dir')
 exist('/docs','dir')


-- Here
doesFileExist "input.txt"
(getDirectories "docs").count == 1
-- Root
doesFileExist "\input.txt"
(getDirectories "C:\docs").count == 1