Solutions by Programming Task

Arithmetic/Integer

C#

using System.Linq;
using static System.Console;

namespace SolutionsByProgrammingTask
{
    internal static class Program
    {
        public static void Main(string[] args)
        {
            var input = ReadLine().Split(' ').Select(int.Parse).ToArray();
            var x = input[0];
            var y = input[1];
            WriteLine($"{x} + {y} = {x + y}");
            WriteLine($"{x} - {y} = {x - y}");
            WriteLine($"{x} * {y} = {x * y}");
            WriteLine($"{x} / {y} = {x / y}");
            WriteLine($"{x} % {y} = {x % y}");
            WriteLine($"{x} to the power of {y} = {System.Math.Pow(x, y)}");
        }
    }
}

Array concatenation

C#

using System.Linq;

namespace SolutionsByProgrammingTask
{
    internal static class Program
    {
        public static void Main(string[] args)
        {
            int[] a = {1, 2, 3};
            int[] b = {4, 5, 6};
            var c = a.Concat(b).ToArray();
        }
    }
}

Associative array/Iteration

C#

using System;
using System.Collections.Generic;

namespace SolutionsByProgrammingTask
{
    internal static class Program
    {
        public static void Main(string[] args)
        {
            var dictionary = new Dictionary<string, int>()
            {
                {"one", 1},
                {"two", 2},
                {"three", 3}
            };
            foreach (var i in dictionary)
            {
                Console.WriteLine($"{i.Key} => {i.Value}");
            }
        }
    }
}

Averages/Arithmetic mean

C#

using System.Linq;

namespace SolutionsByProgrammingTask
{
    internal static class Program
    {
        public static void Main(string[] args)
        {
            int[] a = {1, 2, 3};
            var mean = a.Average();
        }
    }
}

Averages/Median

C#

using System.Linq;

namespace SolutionsByProgrammingTask
{
    internal static class Program
    {
        public static void Main(string[] args)
        {
            int[] a = {1, 2, 3};
            var b = a.OrderBy(i => i).ToArray();
            if (a.Length%2==1)
            {
                var median = b[b.Length/2+1];
            }
            else
            {
                var median = b.Skip(b.Length / 2 - 1).Take(2).Average();
            }
        }
    }
}

Averages/Root mean square

C#

using System.Linq;
using static System.Math;

namespace SolutionsByProgrammingTask
{
    internal static class Program
    {
        public static void Main(string[] args)
        {
            int[] a = {1, 2, 3};
            var rootMeanSquare = Sqrt(a.Sum(i => i * i) / a.Length);
        }
    }
}

Binary digits

C#

using System;

namespace SolutionsByProgrammingTask
{
    internal static class Program
    {
        public static void Main(string[] args)
        {
            var x = 9000;
            Console.WriteLine(Convert.ToString(x,2));
        }
    }
}

Count occurrences of a substring

C#

using static System.Console;

namespace SolutionsByProgrammingTask
{
    internal static class Program
    {
        public static void Main(string[] args)
        {
            var a = ReadLine();
            var b = ReadLine();
            WriteLine(a.Split(b).Length - 1);
        }
    }
}

Create a file

C#

using System.IO;

namespace SolutionsByProgrammingTask
{
    internal static class Program
    {
        public static void Main(string[] args)
        {
            File.Create("output.txt");
            Directory.CreateDirectory("docs");
        }
    }
}

Create a two-dimensional array at runtime

C#

using static System.Console;
using System.Linq;

namespace SolutionsByProgrammingTask
{
    internal static class Program
    {
        public static void Main(string[] args)
        {
            var input = ReadLine().Split(' ').Select(int.Parse).ToArray();
            var arr = new int[input[0], input[1]];
        }
    }
}

Date format

C#

using System;
using static System.Console;

namespace SolutionsByProgrammingTask
{
    internal static class Program
    {
        public static void Main(string[] args)
        {
            var dt = DateTime.Now.Date;
            WriteLine(dt.ToString("yyyy-MM-dd"));
            WriteLine(dt.ToString("dddd, MMMM dd, yyyy"));
        }
    }
}

Day of the week

C#

using System;
using static System.Console;
using System.Linq;

namespace SolutionsByProgrammingTask
{
    internal static class Program
    {
        public static void Main(string[] args)
        {
            Enumerable.Range(2008, 2121 - 2007)
                .Select(y => new DateTime(y, 12, 25))
                .Where(d => d.DayOfWeek == DayOfWeek.Sunday)
                .Select(d => d.ToString("yyyy"))
                .ToList()
                .ForEach(WriteLine);
        }
    }
}

Delete a file

C#

using System.IO;

namespace SolutionsByProgrammingTask
{
    internal static class Program
    {
        public static void Main(string[] args)
        {
            File.Delete("input.txt");
            Directory.Delete("docs");
        }
    }
}

Dot product

C#

using static System.Console;
using System.Linq;

namespace SolutionsByProgrammingTask
{
    internal static class Program
    {
        public static void Main(string[] args)
        {
            int[] a = { 1, 2, 3 };
            int[] b = { 4, 5, 6 };
            WriteLine(a.Zip(b, (x, y) => x * y).Sum());
        }
    }
}

Fibonacci sequence

Batch File

@echo off
setlocal enabledelayedexpansion
call :fib %1 res
echo %res%
exit /b %errorlevel%

:fib
if %1 equ 0 (
    set "%~2=0"
    exit /b 0
)
set "p=0"
set "n=1"
set /a e=%1-1
for /l %%i in (1,1,%e%) do (
    set /a s=!p!+!n!
    set "p=!n!"
    set "n=!s!"
)
set "%~2=%n%"
exit /b 0

FizzBuzz

C#

using System;
using System.Linq;

namespace SolutionsByProgrammingTask
{
    internal static class Program
    {
        public static void Main(string[] args)
        {
            Enumerable.Range(1, 100).ToList().ForEach(i => Console.WriteLine(i % 5 == 0 ? i % 3 == 0 ? "FizzBuzz" : "Buzz" : i % 3 == 0 ? "Fizz" : i.ToString()));
        }
    }
}

Generate lower case ASCII alphabet

C#

using static System.Console;
using System.Linq;

namespace SolutionsByProgrammingTask
{
    internal static class Program
    {
        public static void Main(string[] args)
        {
            Enumerable.Range('a', 26).ToList().ForEach(i => Write((char)i));
        }
    }
}

Execute Brainfuck

F#

open System

let rec Input _ =
    match Console.ReadLine() with
    | "" -> ""
    | s -> s + Input()

let next (l, h::t) = h::l, t
let previous (h::t, l) = t, h::l

let check = function
    | [], [] -> [0], [0]
    | [], r -> [0], r
    | l, [] -> l, [0]
    | a ->a

let rec skipPrevious p =
    match p with
    | ('['::_, _) -> previous p 
    | _ -> skipPrevious << previous <| p

let rec skipNext p =
    match p with
    | (_, '['::_) | (_, ']'::_) -> p
    | _ -> skipNext << next <| p

let rec Interpreter p d =
    match p,d with
    | (_, []), _ -> ()
    | (_, '>'::_), _ -> Interpreter (next p) (check << next <| d)
    | (_, '<'::_), _ -> Interpreter (next p) (check << previous <| d)
    | (_, '+'::_), (l, 255::t) -> Interpreter (next p) (l, 0::t)
    | (_, '+'::_), (l, h::t) -> Interpreter (next p) (l, (h + 1)::t)
    | (_, '-'::_), (l, 0::t) -> Interpreter (next p) (l, 255::t)
    | (_, '-'::_), (l, h::t) -> Interpreter (next p) (l, (h - 1)::t)
    | (_, ','::_), (l, _::t) -> Interpreter (next p) (l, (Console.ReadLine() |> Int32.Parse)::t)
    | (_, '.'::_), (_, h::_) -> (char)h |> Console.Write |> (fun _ -> Interpreter (next p) d)
    | (_, '['::_), (_, 0::_) -> Interpreter (skipNext << next <| p) d
    | (_, '['::_), _ | (_, ']'::_), (_, 0::_) -> Interpreter (next p) d
    | (_, ']'::_), _ -> Interpreter (skipPrevious << previous <| p) d

[<EntryPoint>]
let main _ = 
    let rec loop i =
        Console.ForegroundColor <- ConsoleColor.Yellow
        Console.Write ("bf(" + i.ToString() + ")->")
        Console.ForegroundColor <- ConsoleColor.White
        Interpreter ([], List.ofArray <| Input().ToCharArray()) ([0], [0])
        loop (i + 1)
    loop 0
    0

Closest-pair problem

F#

open System.Windows

let ClosestPairs (points:Point []) =
    let n = points.Length - 1
    in seq {
        for i in 0..n-1 do
            for j in i+1..n do
                yield points.[i], points.[j]
    }
    |> Seq.minBy (fun (a, b) -> (b - a).LengthSquared)

Convex Hull

F#

open System.Windows
open System.Collections.Generic

let ConvexHull (points:List<Point>) =
    points.Sort(fun a b -> a.X.CompareTo(b.X))
    let res = List<Point>()
    let ccw (a:Point) (b:Point) (c:Point) = (b.X - a.X) * (c.Y - a.Y) > (b.Y - a.Y) * (c.X - a.X)
    for p in points do
        while res.Count >= 2 && not <| ccw res.[res.Count - 2] res.[res.Count - 1] p do
            res.RemoveAt (res.Count - 1)
        res.Add p

    let t = res.Count + 1
    for i = points.Count - 1 downto 0 do
        let p = points.[i]
        while res.Count >= t && not <| ccw res.[res.Count - 2] res.[res.Count - 1] p do
            res.RemoveAt (res.Count - 1)
        res.Add p
    res.RemoveAt (res.Count - 1)
    res

Ethiopian Multiplication

F#

let EthiopianMultiplication x y =
    let rec em x y r =
        match x with
        | 1 -> y + r
        | x when x % 2 = 0 -> em (x / 2) (y * 2) r
        | _ -> em ((x - 1) / 2) (y * 2) (r + y)
    em x y 0

Hello world/Text

Brainfuck

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
+++++++++++++++++++++++++++++.
+++++++.
.
+++.
-------------------------------------------------------------------------------.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.
--------.
+++.
------.
--------.
-------------------------------------------------------------------.
-----------------------.

Integer sequence

Brainfuck

.+[.+]

Catamorphism

C#

using static System.Console;
using System.Linq;

namespace Catamorphism
{
    class Catamorphism
    {
        static void Main(string[] args)
        {
            var lst = Enumerable.Range(1, 5);
            WriteLine(lst.Aggregate((a, b) => a + b));
            WriteLine(lst.Aggregate(0, (a, b) => a + b));
            WriteLine(lst.Reverse().Aggregate((a, b) => a + b));
            WriteLine(lst.Reverse().Aggregate(0, (a, b) => a + b));
        }
    }
}

C++

#include <numeric>
#include <vector>
#include <iostream>

template<typename T, typename... Args>
T LeftFold(T init, Args&&... args)
{
	return (init + ... + args);
}

template<typename T, typename... Args>
T RightFold(T init, Args&&... args)
{
	return (args + ... + init);
}

template<typename... Args>
auto LeftFoldWithoutInitialValue(Args&&... args)
{
	return (... + args);
}

template<typename... Args>
auto RightFoldWithoutInitialValue(Args&&... args)
{
	return (args + ...);
}

int main()
{
	std::vector<int> lst = { 1,2,3,4,5 };
	std::cout << std::accumulate(lst.begin(), lst.end(), 0) << std::endl;
	std::cout << std::accumulate(lst.begin(), lst.end(), 0, std::plus<int>()) << std::endl;
	std::cout << std::accumulate(lst.begin(), lst.end(), 0, [](auto a, auto b) { return a + b; }) << std::endl;
	std::cout << std::accumulate(lst.rbegin(), lst.rend(), 0, std::plus<int>()) << std::endl;
	std::cout << LeftFold(0, 1, 2, 3, 4, 5) << std::endl;
	std::cout << RightFold(0, 1, 2, 3, 4, 5) << std::endl;
	std::cout << LeftFoldWithoutInitialValue(0, 1, 2, 3, 4, 5) << std::endl;
	std::cout << RightFoldWithoutInitialValue(0, 1, 2, 3, 4, 5) << std::endl;
}

C

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

void* Redece(void* (*func)(void*, void*), void** lst, uint32_t size)
{
	void* res = *lst;
	for (uint32_t i = 1; i < size; i++) res = func(res, lst[i]);
	return res;
}

void* Fold(void* (*func)(void*, void*), void** lst, uint32_t size, void* init)
{
	void* res = init;
	for (uint32_t i = 0; i < size; i++) res = func(res, lst[i]);
	return res;
}

int Add(int a, int b)
{
	return a + b;
}

void main()
{
	int lst[] = { 1, 2, 3, 4, 5 };
	printf("%d\n", Redece(Add, lst, 5));
	printf("%d", Fold(Add, lst, 5, 1));
}

F#

> let lst = [1 .. 5];;
val lst : int list = [1; 2; 3; 4; 5]

> List.reduce (+) lst;;
val it : int = 15

> List.reduceBack (+) lst;;
val it : int = 15

> List.fold (+) 0 lst;;
val it : int = 15

> List.foldBack (+) lst 0;;
val it : int = 15

> Seq.unfold (fun (a, b) -> Some(a,(b,b+1))) (1,2);;
val it : seq<int> = seq [1; 2; 3; 4; ...]

Sorting algorithms/Bubble sort

C++

#include <iterator>

template <typename T>
void BubbleSort(T begin, T end)
{
	auto swapped = true;
	while (begin != end-- && swapped)
	{
		swapped = false;
		for (auto i = begin; i != end; ++i)
		{
			if (*i > *(i + 1))
			{
				std::iter_swap(i, i + 1);
				swapped = true;
			}
		}
	}
}

F#

let BubbleSort lst =
    let rec bs acc tail succ =
        match tail, succ with
        | [], true -> acc
        | [], _ -> bs [] acc true
        | x::y::t, _ when x > y -> bs (acc@[y]) (x::t) false
        | h::t, _ -> bs (acc@[h]) t succ
    bs [] lst true

Sorting algorithms/Insertion sort

C++

// Binary
#include <algorithm>
template<typename T>
void BinaryInsertionSort(T begin, T end)
{
	for (auto i = begin; i != end; ++i) std::rotate(std::upper_bound(begin, i, *i), i, i + 1);
}

Sorting algorithms/Quick Sort

C++

#include <algorithm>
#include <functional>

template <typename T>
void QuickSort(T first, T last)
{
	if (last - first < 2) return;
	auto split = std::partition(first + 1, last, std::bind2nd(std::less<typename std::iterator_traits<T>::value_type>(), *first));
	std::iter_swap(first, split - 1);
	QuickSort(first, split - 1);
	QuickSort(split, last);
}

F#

let rec QuickSort = function
    | h::t ->
        let l, r = List.partition ((>=) h) t
        in (QuickSort l) @ (h::QuickSort r)
    | _ -> []
// multi-process
let rec QuickSortAsync lst = 
    match lst with
    | h::t ->
        let l, r = List.partition ((>=) h) t
        let task = 
            [QuickSortAsync l; QuickSortAsync r]
            |> Async.Parallel
            |> Async.RunSynchronously
        async{ return (task.[0]) @ (h::(task.[1])) }
    | _ -> async{ return [] }

Sorting algorithms/Selection sort

C++

#include <algorithm>

template <typename T>
void SelectionSort(T first, T last)
{
	for (auto i = first; i != last; ++i) std::iter_swap(i, std::min_element(i, last));
}

F#

let rec SelectionSort = function
    | h::t ->
        let min, tail = List.fold (fun (min, acc) x -> if x < min then (x, min::acc) else (min, x::acc)) (h, []) t
        in min::SelectionSort tail
    | _ -> []

Fibonacci sequence

Bash

#!/bin/bash

#Iterative
fib() 
{
    p=0
    n=1
    for ((i=0;i<$1;++i)) do
        sum=$(($p+$n))
        p=$n
        n=$sum
    done
    echo $p
    return $p
}

Batch File

@echo off
setlocal enabledelayedexpansion
call :fib %1 res
echo %res%
exit /b %errorlevel%

:fib
if %1 equ 0 (
    set "%~2=0"
    exit /b 0
)
set "p=0"
set "n=1"
set /a e=%1-1
for /l %%i in (1,1,%e%) do (
    set /a s=!p!+!n!
    set "p=!n!"
    set "n=!s!"
)
set "%~2=%n%"
exit /b 0

Brainfuck

,->>+<<[->[->>+<<]>[-<+>>+<]>[-<+>]<<<]>>.

Run in bash
printf \\$(printf '%03o' `read x && echo $x`) | bf Iterative.bf | od -t d1 -A none

MATLAB

function [res] = MatrixFib(x)
    r = [1 1; 1 0] ^ (x - 1);
    res = r(1, 1);
end

MAXScript

fn fib x =
(
	if x < 1 then
	(
		0
	)
	else
	(
		prev = 0
		next = 1
		for i in 1 to x - 1 do
		(
			sum = prev + next
			prev = next
			next = sum
		)
		next
	)
)

messageBox(fib(10) as string)

Mathematica

(* built-in *)
Fibonacci[10]
(* iterative *)
fib[x_] := Block[{p = 0, n = 1, sum},
  For[i = 0, i < x - 1 , i++,
    sum = p + n;
    p = n;
    n = sum];
  Return[n]]
(* math *)
fib[x_] := N[(2^-x ((1 + Sqrt[5])^x - (-1 + Sqrt[5])^x Cos[Pi x]))/Sqrt[5]]
(* matrix *)
fib[x_] := MatrixPower[{{1, 1}, {1, 0}}, x - 1][[1, 1]]
(* recursive *)
fib[0] = 0
fib[1] = 1
fib[x_] := fib[x - 1] + fib[x - 2]

PowerShell

function fib($x)
{
    if($x -lt 2) { return $x }
    $p, $n = 0, 1
    0 .. ($x - 1) | % {$p, $n = $n, ($p + $n)}
    return $p
}

Python

# Accumulate
from itertools import *

Fib = lambda x: list(accumulate(chain([[0, 1]], range(x)),lambda s, x: [s[1],sum(s)]))[-1][0]
# Dictionary
D = {0: 0, 1: 1, 2: 1}
def Fib(x):
    if x in D:
        return D[x]
    f1 = Fib(x // 2 + 1)
    f2 = Fib((x - 1) // 2)
    D[x] = (f1 * f1 + f2 * f2 if x & 1 else f1 * f1 - f2 * f2)
    return D[x]
# Dijkstra
def Fib(x):
    def f(a, b, p, q, i):
        if i == 0:
            return b
        return f(a, b, p * p + q * q, q * q + 2 * p * q, i // 2) if i % 2 == 0 else f(b * q + a * q + a * p, b * p + a * q, p, q, i - 1)
    return f(1, 0, 0, 1, x)
# Iterative
def Fib(x):
    d = [0, 1]
    for i in range(x):
        d = [d[1], sum(d)]
    return d[0]
# Iterative
def Fib(x):
    p = 0
    n = 1
    for i in range(x):
        p, n = n, p + n
    return p
# Math
from math import *

Fib = lambda x : int(2 ** -x * ((1 + sqrt(5)) ** x - (-1 + sqrt(5)) ** x * cos(pi * x)) / sqrt(5))
# Matrix
def Fib(x):
    if x == 0:
        return 0
    def prevPowTwo(x):
        if ((x & -x) == x):
            return x
        else:
            x -= 1
            x |= x >> 1
            x |= x >> 2
            x |= x >> 4
            x |= x >> 8
            x |= x >> 16
            x += 1
            return x / 2
    powTwo = prevPowTwo(x)
    q = r = i = 1
    s = 0
    while(i < powTwo):
        i, q, r, s = i * 2, q * q + r * r, r * (q + s), r * r + s * s
    while(i < x):
        i, q, r, s = i + 1, q + r, q, r
    return r
# Recursive
Fib = lambda x: x if x < 2 else Fib(x - 1) + Fib(x - 2)
# Reduce
from functools import *

Fib = lambda x: reduce(lambda s, x: [s[1],sum(s)], range(x), (0, 1))[0]
# Tail Recursive
def Fib(x):
    f = lambda p, n, i: n if i == 0 else f(p + n, p, i - 1)
    return f(1, 0, x)
# YCombinator
Fib = lambda x: (lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))))(lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2)))(x)

Racket

#| Dijkstra |#

(define (Fib n)
  (let f ((a 1) (b 0) (p 0) (q 1) (i n))
    (cond ((= i 0) b)
          ((even? i)
           (f a
                    b
                    (+ (* p p) (* q q))
                    (+ (* q q) (* 2 p q))
                    (/ i 2)))
          (else
           (f (+ (* b q) (* a q) (* a p))
                    (+ (* b p) (* a q))
                    p
                    q
                    (- i 1))))))
#| Iterative |#

(define (Fib x)
  (do ((i 0 (+ i 1))
       (p 0 n)
       (n 1 (+ p n)))
    ((= i x) p)))
#| Math |#
  
(define (Fib x)
  (round (/
          (*
           (expt 2 (- x))
           (-
            (expt (+ 1 (sqrt 5)) x)
            (*
             (expt (- (sqrt 5) 1) x)
             (cos (* pi x)))))
          (sqrt 5))))
#| Matrix |#
(require math/matrix)

(define (Fib x)
  (matrix-ref
   (matrix-expt
    (matrix ([1 1] [1 0]))
    (- x 1))
   0 0))
#| Recursive |#
  
(define (Fib x)
  (if (< x 2)
      x
      (+ (Fib (- x 1))
         (Fib (- x 2)))))
#| TailRecursive |#
(define (Fib x)
  (let f ((p 1) (n 0) (i x))
    (if (= i 0)
        n
        (f (+ p n) p (- i 1)))))

Ruby

def fib(x)
  p, n = 0, 1
  x.times {p, n = n, p + n}
  p
end

MySQL

-- Iterative

create function Fib(x int) returns int deterministic
begin
    declare p int default 0;
    declare n int default 1;
    declare sum int;
    declare i int default 0;
    while i < x do
        set sum = p + n;
        set p = n;
        set n = sum;
        set i = i + 1;
    end while;
    return p;
end;
-- Math
create function Fib(x int) returns int deterministic return POWER((1 + SQRT(5)) / 2, x) / SQRT(5);
-- Recursive
with recursive Fib(p, n, x) as (select 0, 1, 0 union all select n, p + n, x + 1 from Fib where x < 10) select max(p) from Fib;

Scheme

; Dijkstra

(define (Fib n)
  (let f ((a 1) (b 0) (p 0) (q 1) (i n))
    (cond ((= i 0) b)
          ((even? i)
           (f a
                    b
                    (+ (* p p) (* q q))
                    (+ (* q q) (* 2 p q))
                    (/ i 2)))
          (else
           (f (+ (* b q) (* a q) (* a p))
                    (+ (* b p) (* a q))
                    p
                    q
                    (- i 1))))))
; Iterative

(define (Fib x)
  (do ((i 0 (+ i 1))
       (p 0 n)
       (n 1 (+ p n)))
    ((= i x) p)))
; Math

(define (Fib x)
  (round (/
          (*
           (expt 2 (- x))
           (-
            (expt (+ 1 (sqrt 5)) x)
            (*
             (expt (- (sqrt 5) 1) x)
             (cos (* pi x)))))
          (sqrt 5))))
; Matrix

(define (Fib x)
  (define (matrix-exp mat exp)
    (define (row*col row col)
      (apply + (map * row col)))
    (define (matrix-multiply m1 m2)
      (map 
       (lambda (row) 
         (apply map (lambda col (row*col row col)) m2)) 
       m1))
    (define (square-matrix mat) (matrix-multiply mat mat))
    (define (halve x) (/ x 2))
    (define (dec x) (- x 1))
    (cond ((= exp 1) mat)
          ((even? exp) (square-matrix (matrix-exp mat (halve exp))))
          (else (matrix-multiply mat (matrix-exp mat (dec exp))))))
  (if (< x 10)
      x
      (list-ref (list-ref (matrix-exp '((1 1) (1 0)) (- x 1)) 0) 0)))
; Recursive
(define (Fib x)
  (if (< x 2)
      x
      (+ (Fib (- x 1))
         (Fib (- x 2)))))
; TailRecursive
  
(define (Fib x)
  (let f ((p 1) (n 0) (i x))
    (if (= i 0)
        n
        (f (+ p n) p (- i 1)))))

VBA

Function Fib(x)
    If x < 2 Then Fib = x Else Fib = Fib(x - 1) + Fib(x - 2)
End Function

VBScript

Function Fib(x)
    If x < 2 Then
        Fib = x
    else 
        Fib = Fib(x - 1) + Fib(x - 2)
    End If
End Function

msgbox(fib(inputbox("x:","x")))

Verilog HDL

module Iterative(
	input clk,
	output [7:0] value
);
reg [7:0] x, previous, current, counter;

assign value = previous;

initial begin
	x <= 8'd10;
	previous <= 8'd0;
	current <= 8'd1;
	counter <= 8'd0;
end

always @(posedge clk) begin
	if (counter < x) begin
		counter <= counter + 8'd1;
		current <= current + previous;
		previous <= current;
	end
end
endmodule

Visual Basic .NET

' Iterative

Imports System.Numerics
Function Fib(x As BigInteger) As BigInteger
    If x < 2 Then Return x
    Dim p As BigInteger = 0
    Dim n As BigInteger = 1
    For i = 0 To x - 2
        Dim s = p + n
        p = n
        n = s
    Next
    Return n
End Function
' Math
  
Function Fib(x As Decimal) As Decimal
    Return 2 ^ -x * ((1 + Math.Sqrt(5)) ^ x - (-1 + Math.Sqrt(5)) ^ x * Math.Cos(Math.PI * x)) / Math.Sqrt(5)
End Function
' Matrix
  
Imports System.Windows.Media
Function Fib(x As Integer) As Double
    If x < 2 Then Return x
    Dim matrix = New Matrix(1, 1, 1, 0, 0, 0)
    Dim res = New Matrix(1, 1, 1, 0, 0, 0)
    For i = 0 To x - 3
        res = Matrix.Multiply(res, matrix)
    Next
    Return res.M11
End Function
' Recursive
  
Function Fib(x As Integer) As Integer
    If x < 2 Then Return x
    Return Fib(x - 1) + Fib(x - 2)
End Function

Even or odd

PHP

<?php
//bitwise-and
function IsEven($x)
{
    return ($x & 1) == 0;
}

function IsOdd($x)
{
    return ($x & 1) != 0;
}
<?php
//modular
function IsEven($x)
{
    return $x % 2 == 0;
}

function IsOdd($x)
{
    return $x % 2 != 0;
}

PI approximation

PowerShell

function iter-pi
{
    [OutputType([string])]
    Param ([double]$epsilon)
    $M_PI = 3.14159265358979323846
    $res, $i = 0.0, 0
    while ([Math]::Abs($res * 4 - $M_PI) -gt $epsilon)
    {
        $res += [Math]::Pow(-1, $i) / (2 * $i + 1)
        $i++
    }
    return [String]::Format("[{0:F0}, {1:F10}]", $i, $res * 4);
}

Entropy/Narcissist

C

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

int main()
{
	char count[256] = { 0 };
	FILE* fp = fopen("main.c", "r");
	int len;
	for (len = 0; !feof(fp); ++len)
	{
		count[fgetc(fp)]++;
	}
	fclose(fp);
	double entropy = 0;
	for (int i = 0; i < 256; i++)
	{
		if (count[i])
		{
			double freq = (double)count[i] / len;
			entropy -= freq * log(freq) / log(2);
		}
	}
	printf("%lf\n", entropy);
}

Levenshtein distance

JavaScript

const LevenshteinDistance = (a, b) => {
    const rec = (i, j) => {
        if (i === -1) return j + 1;
        if (j === -1) return i + 1;
        if (a[i] === b[j]) {
            return rec(i - 1, j - 1)
        } else {
            return Math.min(
                rec(i, j - 1) + 1,
                rec(i - 1, j) + 1,
                rec(i - 1, j - 1) + 1);
        }
    };
    return rec(a.length - 1, b.length - 1);
}

Sum of a series

Erlang

lists:sum([1 / math:pow(X, 2) || X <- lists:seq(1, 1000)]).

Random number generator (included)

MySQL

select rand();

Palindrome detection

F#

let PalindromeDetection (str:string) = (Seq.rev str |> System.String.Concat) = str

Finite state machine

PHP

<?php
$status = 'ready';

function getOp($tip)
{
    echo $tip . "\n" . '<- ';
    return strtolower(fgets(STDIN))[0];
};

while ($status != 'exit')
{
    switch ($status)
    {
        case 'ready':
            $op = getOp("ready.\ndeposit/quit");
            if ($op == 'd') $status = 'waiting';
            elseif ($op == 'q') $status = 'exit';
            break;
        case 'waiting':
            $op = getOp("waiting.\nselect/refund");
            if ($op == 's') $status = 'dispense';
            elseif ($op == 'r') $status = 'refunding';
            break;
        case 'dispense':
            if (getOp("dispense.\nremove") == 'r') $status = 'ready';
            break;
        case 'refunding':
            $status = 'ready';
            break;
    }
}

echo 'exit.';

Towers of Hanoi

Racket

#lang racket
(define (TowersOfHanoi ndisks from to via)
  (when (> ndisks 0)
    (TowersOfHanoi (- ndisks 1) from via to)
    (printf "Move disk from ~a to ~a\n" from to)
    (TowersOfHanoi (- ndisks 1) via to from)))

(TowersOfHanoi 5 'left 'middle 'right)

Penrose tiling

C#

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using static System.Math;
using Brushes = System.Drawing.Brushes;
using Image = System.Windows.Controls.Image;
using Rectangle = System.Drawing.Rectangle;

namespace ConsoleApp1
{
    public static class Program
    {
        private static readonly double G = (1 + Sqrt(5)) / 2;
        private const double T = 36 * (PI * 1) / 180;

        private static List<Tile> tiles = new List<Tile>();

        private const int w = 3840;
        private const int h = 2160;

        private enum Type
        {
            Kite,
            Dart
        }

        private struct Tile
        {
            public readonly double x;
            public readonly double y;
            public readonly double angle;
            public readonly double size;
            public readonly Type type;

            public Tile(Type t, double x, double y, double a, double s)
            {
                type = t;
                this.x = x;
                this.y = y;
                angle = a;
                size = s;
            }
        }

        private static BitmapSource Convert(Bitmap bitmap)
        {
            var bitmapData = bitmap.LockBits(
                new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                ImageLockMode.ReadOnly, bitmap.PixelFormat);
            var bitmapSource = BitmapSource.Create(
                bitmapData.Width, bitmapData.Height,
                bitmap.HorizontalResolution, bitmap.VerticalResolution,
                PixelFormats.Bgr32, null,
                bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, bitmapData.Stride);
            bitmap.UnlockBits(bitmapData);
            return bitmapSource;
        }

        private static List<Tile> SetupPrototiles(int w, int h)
        {
            var proto = new List<Tile>();
            for (var a = PI / 2 + T; a < 3 * PI; a += 2 * T)
                proto.Add(new Tile(Type.Kite, w / 2f, h / 2f, a, w / 2.5));
            return proto;
        }

        private static List<Tile> DeflateTiles(List<Tile> tls, int generation)
        {
            while (true)
            {
                if (generation <= 0) return tls;
                var next = new List<Tile>();
                foreach (var tile in tls)
                {
                    double x = tile.x, y = tile.y, a = tile.angle, nx, ny;
                    var size = tile.size / G;

                    if (tile.type == Type.Dart)
                    {
                        next.Add(new Tile(Type.Kite, x, y, a + 5 * T, size));
                        for (int i = 0, sign = 1; i < 2; i++, sign *= -1)
                        {
                            nx = x + Cos(a - 4 * T * sign) * G * tile.size;
                            ny = y - Sin(a - 4 * T * sign) * G * tile.size;
                            next.Add(new Tile(Type.Dart, nx, ny, a - 4 * T * sign, size));
                        }
                    }
                    else
                    {
                        for (int i = 0, sign = 1; i < 2; i++, sign *= -1)
                        {
                            next.Add(new Tile(Type.Dart, x, y, a - 4 * T * sign, size));
                            nx = x + Cos(a - T * sign) * G * tile.size;
                            ny = y - Sin(a - T * sign) * G * tile.size;
                            next.Add(new Tile(Type.Kite, nx, ny, a + 3 * T * sign, size));
                        }
                    }
                }
                tls = next;
                generation -= 1;
            }
        }


        [STAThread]
        private static void Main(string[] args)
        {
            var bmp = new Bitmap(w, h);
            tiles = DeflateTiles(SetupPrototiles(w, h), 5);
            double[,] dist = {{G, G, G}, {-G, -1, -G}};
            using (var g = Graphics.FromImage(bmp))
            {
                foreach (var tile in tiles)
                {
                    var angle = tile.angle - T;
                    var points = new List<PointF> {new PointF((float) tile.x, (float) tile.y)};
                    var ord = (int) tile.type;
                    for (var i = 0; i < 3; i++)
                    {
                        var x = tile.x + dist[ord, i] * Max(tile.size, 1f) * Cos(angle);
                        var y = tile.y - dist[ord, i] * Max(tile.size, 1f) * Sin(angle);
                        points.Add(new PointF((float) x, (float) y));
                        angle += T;
                    }
                    points.Add(new PointF((float) tile.x, (float) tile.y));
                    var arr = points.ToArray();
                    g.FillPolygon(ord == 0 ? Brushes.Orange : Brushes.Yellow, arr);
                    g.DrawPolygon(Pens.DarkGray, arr);
                }
            }
            //bmp.Save(@"z:\test.bmp");
            var image = new Image {Stretch = Stretch.Uniform, Source = Convert(bmp)};
            var windows = new Window {Content = image, Title = "Penrose tiling"};
            new Application().Run(windows);
        }
    }
}

F#

open System.Windows
open System.Windows.Media.Imaging
open System.Collections.Generic
open System.Windows.Media
open System
open System.Drawing

type Type = Kite | Dart

type Tile(typ,x,y,angle,size) =
    member this.Type = typ
    member this.X = x
    member this.Y = y
    member this.Angle = angle
    member this.Size = size

let Convert (bitmap:Bitmap) =
    let bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat)
    let bitmapSource = BitmapSource.Create(bitmapData.Width, bitmapData.Height, float(bitmap.HorizontalResolution), float(bitmap.VerticalResolution), PixelFormats.Bgr32, null, bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, bitmapData.Stride)
    bitmap.UnlockBits(bitmapData)
    bitmapSource

[<System.STAThread>]
do
    let w = 3840
    let h = 2160

    let ToRadians d = d * (Math.PI * 1.) / 180.0
    let G =  (1. + sqrt 5.) / 2.
    let T = ToRadians(36.)

    let proto = new List<Tile>()
    for x in [Math.PI / 2. + T .. 2. * T .. 3. * Math.PI] do
        proto.Add(Tile(Kite, float(w)/2., float(h)/2., x, float(w)/2.5))

    let rec deflateTiles (tiles:List<Tile>) = function
        | 0 -> tiles
        | x ->
            let next = new List<Tile>()
            for tl in tiles do
                let x = tl.X
                let y = tl.Y
                let a = tl.Angle
                let size = tl.Size / G
                match tl.Type with
                | Dart ->
                    next.Add(Tile(Kite, x, y, a + 5. * T, size))
                    for sign in [ 1.; -1. ] do
                        next.Add(Tile(Dart, x + cos(a - 4. * T * sign) * G * tl.Size, y - sin(a - 4. * T * sign) * G * tl.Size, a - 4. * T * sign, size))
                | _ ->
                    for sign in [ 1.; -1. ] do
                        next.Add(Tile(Dart, x, y, a - 4. * T * sign, size))
                        next.Add(Tile(Kite, x + cos(a - T * sign) * G * tl.Size, y - sin(a - T * sign) * G * tl.Size, a + 3. * T * sign, size))
            deflateTiles next (x - 1)

    let tiles = deflateTiles proto 5
    let bmp = new Bitmap(w, h)
    use g = Graphics.FromImage(bmp)
    let dist = [| [|G;G;G|]; [|-G;-1.;-G|] |]
    for tl in tiles do
        let start = [| PointF(float32 tl.X, float32 tl.Y) |]
        let ord = match tl.Type with | Kite -> 0 | _ -> 1
        let move = Array.init 3 (fun i -> tl.Angle - T + T * float(i)) |> Array.mapi (fun i angle ->
            PointF(float32(tl.X + dist.[ord].[i] * tl.Size * cos angle), float32(tl.Y - dist.[ord].[i] * tl.Size * sin angle)))
        let points = Array.concat [| start; move |]
        g.FillPolygon((match tl.Type with | Kite -> Brushes.Orange | _ -> Brushes.Yellow), points)
        g.DrawPolygon(Pens.DarkGray, points)

    let image = Controls.Image(Stretch=Media.Stretch.Uniform)
    image.Source <- Convert bmp
    Window(Content=image, Title="Penrose tiling")
    |> (Application()).Run |> ignore

Semiprime

PHP

<?php

function isSemiprime($x)
{
    $n = 0;
    for ($i = 2; $n < 3 && $x != 1;)
    {
        if (($x % $i) == 0)
        {
            $x /= $i;
            $n++;
        }
        else
        {
            $i++;
        }
    }
    return $n == 2;
}

foreach (range(0,100) as $x) echo (isSemiprime($x) ? "true" : "false") . "\n";

Look-and-say sequence

TypeScript

let lookAndSay = (d, n) => [...Array(n + 1).fill(d + "")].reduce(p => p.replace(/(.)\1*/g, w => w.length + w[0]))

First-class functions

Haskell

a = [sin, cos, flip (**) 3.0]
b = [asin, acos, flip (**) $ 1 / 3]
c = zipWith (.) a b
print $ map (\x -> x 0.5) c

Zero to the zero power

Racket

#lang racket

(printf "~a" (expt 0 0))

Magic squares of odd order

PHP

<?php

function f($n, $x, $y)
{
    return ($x + $y * 2 + 1) % $n;
}

if ($argc != 2) return 1;

$n = intval($argv[1]);
if ($n < 3 || ($n % 2) == 0) return 2;
foreach (range(0,$n) as $i)
{
    foreach (range(0, $n) as $j)
    {
        printf("% 4d", f($n, $n - $j - 1, $i) * $n + f($n, $j, $i) + 1);
    }
    echo "\n";
}
printf("\n Magic Constant: %d.\n", ($n * $n + 1) / 2 * $n);

String interpolation (included)

Racket

#lang racket

(format "Mary had a ~a lamb" "little")

Resistor mesh

Mathematica

n = 10;
d1 = SparseArray[{{i_, i_} -> 1, {i_, j_} /; j - i == 1 -> -1}, {n - 1, n}];
eye = SparseArray[{{i_, i_} -> 1}, n];
d = ArrayFlatten[{{KroneckerProduct[d1, eye]}, {KroneckerProduct[eye, d1]}}];
x = n*1 + 2; y = n*7 + 7;
v = LinearSolve[Transpose[d].d, SparseArray[{x -> 1, y -> -1}, n*n]];
N[v[[x]] - v[[y]], 40]

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注