diff --git a/Task/100-doors/D/100-doors.d b/Task/100-doors/D/100-doors.d deleted file mode 100644 index 65e8f69802..0000000000 --- a/Task/100-doors/D/100-doors.d +++ /dev/null @@ -1,31 +0,0 @@ -import std.stdio, std.algorithm, std.range; - -enum DoorState : bool { closed, open } -alias Doors = DoorState[]; - -Doors flipUnoptimized(Doors doors) pure nothrow { - doors[] = DoorState.closed; - - foreach (immutable i; 0 .. doors.length) - for (int j = i; j < doors.length; j += i + 1) - if (doors[j] == DoorState.open) - doors[j] = DoorState.closed; - else - doors[j] = DoorState.open; - return doors; -} - -Doors flipOptimized(Doors doors) pure nothrow { - doors[] = DoorState.closed; - for (int i = 1; i ^^ 2 <= doors.length; i++) - doors[i ^^ 2 - 1] = DoorState.open; - return doors; -} - -void main() { - auto doors = new Doors(100); - - foreach (const open; [doors.dup.flipUnoptimized, - doors.dup.flipOptimized]) - iota(1, open.length + 1).filter!(i => open[i - 1]).writeln; -} diff --git a/Task/100-doors/Erlang/100-doors.erl b/Task/100-doors/Erlang/100-doors.erl deleted file mode 100644 index 3815a08743..0000000000 --- a/Task/100-doors/Erlang/100-doors.erl +++ /dev/null @@ -1,5 +0,0 @@ -doors() -> - F = fun(X) -> Root = math:pow(X,0.5), Root == trunc(Root) end, - Out = fun(X, true) -> io:format("Door ~p: open~n",[X]); - (X, false)-> io:format("Door ~p: close~n",[X]) end, - [Out(X,F(X)) || X <- lists:seq(1,100)]. diff --git a/Task/100-doors/Factor/100-doors.factor b/Task/100-doors/Factor/100-doors.factor deleted file mode 100644 index 6dccd9b759..0000000000 --- a/Task/100-doors/Factor/100-doors.factor +++ /dev/null @@ -1,23 +0,0 @@ -USING: bit-arrays formatting fry kernel math math.ranges -sequences ; -IN: rosetta.doors - -CONSTANT: number-of-doors 100 - -: multiples ( n -- range ) - 0 number-of-doors rot ; - -: toggle-multiples ( n doors -- ) - [ multiples ] dip '[ _ [ not ] change-nth ] each ; - -: toggle-all-multiples ( doors -- ) - [ number-of-doors [1,b] ] dip '[ _ toggle-multiples ] each ; - -: print-doors ( doors -- ) - [ - swap "open" "closed" ? "Door %d is %s\n" printf - ] each-index ; - -: main ( -- ) - number-of-doors 1 + - [ toggle-all-multiples ] [ print-doors ] bi ; diff --git a/Task/100-doors/Rust/100-doors.rust b/Task/100-doors/Rust/100-doors.rust deleted file mode 100644 index 714291be07..0000000000 --- a/Task/100-doors/Rust/100-doors.rust +++ /dev/null @@ -1,15 +0,0 @@ -fn main() { - let mut door_open = [false, ..100]; - - for uint::range(1, 101) |pass| { - for uint::range(1, 101) |door| { - if door % pass == 0 { - door_open[door - 1] = !door_open[door - 1] - } - }; - } - for door_open.eachi |i, state| { - io::println(fmt!("Door %u is %s.", i + 1, - if *state { "open" } else { "closed" })); - } -} diff --git a/Task/24-game/Racket/24-game.rkt b/Task/24-game/Racket/24-game.rkt deleted file mode 100644 index c4efb35a87..0000000000 --- a/Task/24-game/Racket/24-game.rkt +++ /dev/null @@ -1,50 +0,0 @@ -#lang racket - -(define (random-4) - (sort (for/list ((i (in-range 4))) - (add1 (random 9))) - <)) - -(define (check-valid-chars lst-nums str) - (define regx (string-join (list - "^[" - (string-join (map number->string lst-nums) "") - "\\(\\)\\+\\-\\/\\*\\ ]*$") - "")) - (regexp-match? regx str)) - -(define (check-all-numbers lst-nums str) - (equal? - (sort - (map (λ (x) (string->number x)) - (regexp-match* "([0-9])" str)) <) - lst-nums)) - -(define (start-game) - (display "** 24 **\n") - (display "Input \"q\" to quit or your answer in Racket ") - (display "notation, like (- 1 (* 3 2))\n\n") - (new-question)) - -(define (new-question) - (define numbers (random-4)) - (apply printf "Your numbers: ~a - ~a - ~a - ~a\n" numbers) - (define (do-loop) - (define user-expr (read-line)) - (cond - [(equal? user-expr "q") - (exit)] - [(not (check-valid-chars numbers user-expr)) - (display "Your expression seems invalid, please retry:\n") - (do-loop)] - [(not (check-all-numbers numbers user-expr)) - (display "You didn't use all the provided numbers, please retry:\n") - (do-loop)] - [(if (equal? 24 (eval (with-input-from-string user-expr read) (make-base-namespace))) - (display "OK!!") - (begin - (display "Incorrect\n") - (do-loop)))])) - (do-loop)) - -(start-game) diff --git a/Task/99-Bottles-of-Beer/AutoIt/99-bottles-of-beer.autoit b/Task/99-Bottles-of-Beer/AutoIt/99-bottles-of-beer.autoit deleted file mode 100644 index 2d8243ba91..0000000000 --- a/Task/99-Bottles-of-Beer/AutoIt/99-bottles-of-beer.autoit +++ /dev/null @@ -1,21 +0,0 @@ -local $bottleNo=99 -local $lyrics=" " - -While $bottleNo<>0 - If $bottleNo=1 Then - $lyrics&=$bottleNo & " bottles of beer on the wall" & @CRLF - $lyrics&=$bottleNo & " bottles of beer" & @CRLF - $lyrics&="Take one down, pass it around" & @CRLF - Else - $lyrics&=$bottleNo & " bottles of beer on the wall" & @CRLF - $lyrics&=$bottleNo & " bottles of beer" & @CRLF - $lyrics&="Take one down, pass it around" & @CRLF - EndIf - If $bottleNo=1 Then - $lyrics&=$bottleNo-1 & " bottle of beer" & @CRLF - Else - $lyrics&=$bottleNo-1 & " bottles of beer" & @CRLF - EndIf - $bottleNo-=1 -WEnd -MsgBox(1,"99",$lyrics) diff --git a/Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer.sql b/Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer.sql deleted file mode 100644 index f191022cf4..0000000000 --- a/Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer.sql +++ /dev/null @@ -1,29 +0,0 @@ -DELIMITER $$ -DROP PROCEDURE IF EXISTS bottles_$$ -CREATE pROCEDURE `bottles_`(inout bottle_count int, inout song text) -BEGIN -declare bottles_text varchar(30); - - -IF bottle_count > 0 THEN - - - if bottle_count != 1 then - set bottles_text := ' bottles of beer '; - else set bottles_text = ' bottle of beer '; - end if; - - SELECT concat(song, bottle_count, bottles_text, ' \n') INTO song; - SELECT concat(song, bottle_count, bottles_text, 'on the wall\n') INTO song; - SELECT concat(song, 'Take one down, pass it around\n') into song; - SELECT concat(song, bottle_count -1 , bottles_text, 'on the wall\n\n') INTO song; - set bottle_count := bottle_count -1; - CALL bottles_( bottle_count, song); - END IF; -END$$ - -set @bottles=99; -set max_sp_recursion_depth=@bottles; -set @song=''; -call bottles_( @bottles, @song); -select @song; diff --git a/Task/A+B/CoffeeScript/a+b.coffee b/Task/A+B/CoffeeScript/a+b.coffee deleted file mode 100644 index 6a5ab62a7c..0000000000 --- a/Task/A+B/CoffeeScript/a+b.coffee +++ /dev/null @@ -1,14 +0,0 @@ - - - - -
-
- - diff --git a/Task/A+B/Julia/a+b.julia b/Task/A+B/Julia/a+b.julia deleted file mode 100644 index a6513cfc2e..0000000000 --- a/Task/A+B/Julia/a+b.julia +++ /dev/null @@ -1,6 +0,0 @@ -#A+B -function AB() - input = sum(map(int,split(readline(STDIN)," "))) - println(input) -end -AB() diff --git a/Task/Abstract-type/Julia/abstract-type.julia b/Task/Abstract-type/Julia/abstract-type.julia deleted file mode 100644 index a27849a327..0000000000 --- a/Task/Abstract-type/Julia/abstract-type.julia +++ /dev/null @@ -1,2 +0,0 @@ -abstract «name» -abstract «name» <: «supertype» diff --git a/Task/Ackermann-function/Java/ackermann-function.java b/Task/Ackermann-function/Java/ackermann-function.java deleted file mode 100644 index 55feb01b0a..0000000000 --- a/Task/Ackermann-function/Java/ackermann-function.java +++ /dev/null @@ -1,8 +0,0 @@ -import java.math.BigInteger; - -public static BigInteger ack(BigInteger m, BigInteger n) { - return m.equals(BigInteger.ZERO) - ? n.add(BigInteger.ONE) - : ack(m.subtract(BigInteger.ONE), - n.equals(BigInteger.ZERO) ? BigInteger.ONE : ack(m, n.subtract(BigInteger.ONE))); -} diff --git a/Task/Ackermann-function/Julia/ackermann-function.julia b/Task/Ackermann-function/Julia/ackermann-function.julia deleted file mode 100644 index 976ced7de6..0000000000 --- a/Task/Ackermann-function/Julia/ackermann-function.julia +++ /dev/null @@ -1,12 +0,0 @@ -function ack(m,n) - if m == 0 - return n + 1 - elseif n == 0 - return ack(m-1,1) - else - return ack(m-1,ack(m,n-1)) - end -end - -#One-liner -ack2(m,n) = m == 0 ? n + 1 : n == 0 ? ack2(m-1,1) : ack2(m-1,ack2(m,n-1)) diff --git a/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams.d b/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams.d deleted file mode 100644 index 778ab9f358..0000000000 --- a/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams.d +++ /dev/null @@ -1,28 +0,0 @@ -import std.stdio, std.file, std.string, std.algorithm, - std.typecons, std.range; - -auto findDeranged(in string[] words) /*pure nothrow*/ { - Tuple!(string, string)[] result; - foreach (immutable i, const w1; words) - foreach (const w2; words[i + 1 .. $]) - if (zip(w1, w2).all!q{ a[0] != a[1] }()) - result ~= tuple(w1, w2); - return result; -} - -void main() { - Appender!(string[])[30] wClasses; - foreach (word; std.algorithm.splitter(readText("unixdict.txt"))) - wClasses[$ - word.length] ~= word; - auto r = wClasses[].map!q{ a.data }().filter!q{ a.length }(); - writeln("Longest deranged anagrams:"); - foreach (words; r) { - string[][const ubyte[]] anags; // Assume input is ASCII. - foreach (w; words) - anags[(cast(ubyte[])w).sort().release().idup] ~= w.idup; - auto pairs = anags.byValue.filter!q{ a.length > 1 }() - .map!findDeranged().filter!q{ a.length }(); - if (!pairs.empty) - return writefln(" %s, %s", pairs.front[0].tupleof); - } -} diff --git a/Task/Anagrams/AWK/anagrams.awk b/Task/Anagrams/AWK/anagrams.awk deleted file mode 100644 index deb36cc1fb..0000000000 --- a/Task/Anagrams/AWK/anagrams.awk +++ /dev/null @@ -1,26 +0,0 @@ -# JUMBLEA.AWK - words with the most duplicate spellings -# syntax: GAWK -f JUMBLEA.AWK UNIXDICT.TXT -{ for (i=1; i<=NF; i++) { - w = sortstr(toupper($i)) - arr[w] = arr[w] $i " " - n = gsub(/ /,"&",arr[w]) - if (max_n < n) { max_n = n } - } -} -END { - for (w in arr) { - if (gsub(/ /,"&",arr[w]) == max_n) { - printf("%s\t%s\n",w,arr[w]) - } - } - exit(0) -} -function sortstr(str, i,j,leng) { - leng = length(str) - for (i=2; i<=leng; i++) { - for (j=i; j>1 && substr(str,j-1,1) > substr(str,j,1); j--) { - str = substr(str,1,j-2) substr(str,j,1) substr(str,j-1,1) substr(str,j+1) - } - } - return(str) -} diff --git a/Task/Anagrams/Java/anagrams.java b/Task/Anagrams/Java/anagrams.java deleted file mode 100644 index 603b714186..0000000000 --- a/Task/Anagrams/Java/anagrams.java +++ /dev/null @@ -1,30 +0,0 @@ -import java.net.*; -import java.io.*; -import java.util.*; - -public class WordsOfEqChars { - public static void main(String[] args) throws IOException { - URL url = new URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt"); - InputStreamReader isr = new InputStreamReader(url.openStream()); - BufferedReader reader = new BufferedReader(isr); - - Map> anagrams = new HashMap>(); - String word; - int count = 0; - while ((word = reader.readLine()) != null) { - char[] chars = word.toCharArray(); - Arrays.sort(chars); - String key = new String(chars); - if (!anagrams.containsKey(key)) - anagrams.put(key, new ArrayList()); - anagrams.get(key).add(word); - count = Math.max(count, anagrams.get(key).size()); - } - - reader.close(); - - for (Collection ana : anagrams.values()) - if (ana.size() >= count) - System.out.println(ana); - } -} diff --git a/Task/Anagrams/REXX/anagrams.rexx b/Task/Anagrams/REXX/anagrams.rexx deleted file mode 100644 index d961aff93b..0000000000 --- a/Task/Anagrams/REXX/anagrams.rexx +++ /dev/null @@ -1,33 +0,0 @@ -/*REXX program finds words with the largest set of anagrams (same size).*/ -ifid='unixdict.txt'; words=0 /*input file identifier, # words.*/ -wL.=0 /*number of words of length L. */ - do j=1 while lines(ifid)\==0 /*read each word in file (word=X)*/ - x=space(linein(ifid),0) /*pick off a word from the input.*/ - L=length(x); if L<3 then iterate /*onesies and twosies can't win. */ - words=words+1 /*count of (useable) words. */ - @.words=x /*save the word in an array. */ - wL.L=wL.L+1; _=wL.L /*counter of words of length L. */ - @@.L._=x /*array of words of length L. */ - /*sort the letters*/ do ja=1 for L; !.ja=substr(x,ja,1); end - !.0=L; call esort;z=; do jb=1 for L; z=z || !.jb; end - @@s.L._=z /*store the sorted word (letters)*/ - @s.words=@@s.L._ /*and also, sorted length L vers.*/ - end /*j*/ -a.= /*all the anagrams for word X. */ -say copies('─',30) words 'words in the dictionary file: ' ifid -n.=0 /*number of anagrams for word X. */ - do j=1 for words /*process the usable words found.*/ - x=@.j; Lx=length(x); xs=@s.j /*get some vital statistics for X*/ - do k=1 for wL.Lx /*process all the words of len L.*/ - if xs\==@@s.Lx.k then iterate /*is this a true anagram of X ? */ - if x==@@.Lx.k then iterate /*skip doing anagram on itself. */ - n.j=n.j+1; a.j=a.j @@.Lx.k /*bump counter, add ──► anagrams.*/ - end /*k*/ - end /*j*/ -m=n.1 /*assume first (len=1) is largest*/ - do j=2 to words; m=max(m,n.j); end /*find the maximum anagram count.*/ - do k=1 for words; if n.k==m then if word(a.k,1)>@.k then say @.k a.k; end -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────ESORT───────────────────────────────*/ -esort:procedure expose !.;h=!.0;do while h>1;h=h%2;do i=1 for !.0-h;j=i;k=h+i -do while !.k=j then leave;j=j-h;k=k-h;end;end;end;return diff --git a/Task/Arithmetic-geometric-mean/Perl-6/arithmetic-geometric-mean.pl6 b/Task/Arithmetic-geometric-mean/Perl-6/arithmetic-geometric-mean.pl6 deleted file mode 100644 index a3e9b4cf9c..0000000000 --- a/Task/Arithmetic-geometric-mean/Perl-6/arithmetic-geometric-mean.pl6 +++ /dev/null @@ -1,11 +0,0 @@ -sub agm ($a, $g) { - sub iter ($old) { - my $new := [ 0.5 * [+](@$old), sqrt [*](@$old) ]; - last if $new ~~ $old; - $new; - } - - ([$a,$g], &iter ... 0)[*-1][0]; -} - -say agm 1, 1/sqrt 2; diff --git a/Task/Array-concatenation/C++/array-concatenation.cpp b/Task/Array-concatenation/C++/array-concatenation.cpp deleted file mode 100644 index 1dea6457b5..0000000000 --- a/Task/Array-concatenation/C++/array-concatenation.cpp +++ /dev/null @@ -1,14 +0,0 @@ -#include -#include - -int main() -{ - std::vector a(3), b(4); - a[0] = 11; a[1] = 12; a[2] = 13; - b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24; - - a.insert(a.end(), b.begin(), b.end()); - - for (int i = 0; i < a.size(); ++i) - std::cout << "a[" << i << "] = " << a[i] << "\n"; -} diff --git a/Task/Arrays/D/arrays.d b/Task/Arrays/D/arrays.d deleted file mode 100644 index 60d4d9eebf..0000000000 --- a/Task/Arrays/D/arrays.d +++ /dev/null @@ -1,41 +0,0 @@ -// All D arrays are capable of bounds checks. - -import std.stdio, core.stdc.stdlib; -import std.container: Array; - -void main() { - // GC-managed heap allocated dynamic array: - auto array1 = new int[1]; - array1[0] = 1; - array1 ~= 3; // append a second item - // array1[10] = 4; // run-time error - writeln("A) Element 0: ", array1[0]); - writeln("A) Element 1: ", array1[1]); - - // Stack-allocated fixed-size array: - int[5] array2; - array2[0] = 1; - array2[1] = 3; - // array2[2] = 4; // compile-time error - writeln("B) Element 0: ", array2[0]); - writeln("B) Element 1: ", array2[1]); - - // Stack-allocated dynamic fixed-sized array, - // length known only at run-time: - int n = 2; - int[] array3 = (cast(int*)alloca(n * int.sizeof))[0 .. n]; - array3[0] = 1; - array3[1] = 3; - // array3[10] = 4; // run-time error - writeln("C) Element 0: ", array3[0]); - writeln("C) Element 1: ", array3[1]); - - // Phobos-defined heap allocated not GC-managed array: - Array!int array4; - array4.length = 2; - array4[0] = 1; - array4[1] = 3; - // array4[10] = 4; // run-time exception - writeln("D) Element 0: ", array4[0]); - writeln("D) Element 1: ", array4[1]); -} diff --git a/Task/Assertions/PARI-GP/assertions.pari b/Task/Assertions/PARI-GP/assertions.pari deleted file mode 100644 index 4007269324..0000000000 --- a/Task/Assertions/PARI-GP/assertions.pari +++ /dev/null @@ -1,10 +0,0 @@ -#include - -void -test() -{ - int a; - // ... input or change a here - - assert(a == 42); // Aborts program if a is not 42, unless the NDEBUG macro was defined -} diff --git a/Task/Atomic-updates/Haskell/atomic-updates.hs b/Task/Atomic-updates/Haskell/atomic-updates.hs deleted file mode 100644 index caf45cad8a..0000000000 --- a/Task/Atomic-updates/Haskell/atomic-updates.hs +++ /dev/null @@ -1,69 +0,0 @@ -module AtomicUpdates (main) where - -import Control.Concurrent (forkIO, threadDelay) -import Control.Concurrent.MVar (MVar, newMVar, readMVar, modifyMVar_) -import Control.Monad (forever, forM_) -import Data.IntMap (IntMap, (!), toAscList, fromList, adjust) -import System.Random (randomRIO) -import Text.Printf (printf) - -------------------------------------------------------------------------------- - -type Index = Int -type Value = Integer -data Buckets = Buckets Index (MVar (IntMap Value)) - -makeBuckets :: Int -> IO Buckets -size :: Buckets -> Index -currentValue :: Buckets -> Index -> IO Value -currentValues :: Buckets -> IO (IntMap Value) -transfer :: Buckets -> Index -> Index -> Value -> IO () - -------------------------------------------------------------------------------- - -makeBuckets n = do v <- newMVar (fromList [(i, 100) | i <- [1..n]]) - return (Buckets n v) - -size (Buckets n _) = n - -currentValue (Buckets _ v) i = fmap (! i) (readMVar v) -currentValues (Buckets _ v) = readMVar v - -transfer b@(Buckets n v) i j amt | amt < 0 = transfer b j i (-amt) - | otherwise = do - modifyMVar_ v $ \map -> let amt' = min amt (map ! i) - in return $ adjust (subtract amt') i - $ adjust (+ amt') j - $ map - -------------------------------------------------------------------------------- - -roughen, smooth, display :: Buckets -> IO () - -pick buckets = randomRIO (1, size buckets) - -roughen buckets = forever loop where - loop = do i <- pick buckets - j <- pick buckets - iv <- currentValue buckets i - transfer buckets i j (iv `div` 3) - -smooth buckets = forever loop where - loop = do i <- pick buckets - j <- pick buckets - iv <- currentValue buckets i - jv <- currentValue buckets j - transfer buckets i j ((iv - jv) `div` 4) - -display buckets = forever loop where - loop = do threadDelay 1000000 - bmap <- currentValues buckets - putStrLn (report $ map snd $ toAscList bmap) - report list = "\nTotal: " ++ show (sum list) ++ "\n" ++ bars - where bars = concatMap row $ map (*40) $ reverse [1..5] - row lim = printf "%3d " lim ++ [if x >= lim then '*' else ' ' | x <- list] ++ "\n" - -main = do buckets <- makeBuckets 100 - forkIO (roughen buckets) - forkIO (smooth buckets) - display buckets diff --git a/Task/Atomic-updates/Java/atomic-updates.java b/Task/Atomic-updates/Java/atomic-updates.java deleted file mode 100644 index 60b0c18c33..0000000000 --- a/Task/Atomic-updates/Java/atomic-updates.java +++ /dev/null @@ -1,119 +0,0 @@ -import java.util.Arrays; -import java.util.Random; - -public class AtomicUpdates -{ - public static class Buckets - { - private final int[] data; - - public Buckets(int[] data) - { - this.data = data.clone(); - } - - public int getBucket(int index) - { - synchronized (data) - { return data[index]; } - } - - public int transfer(int srcBucketIndex, int destBucketIndex, int amount) - { - if (amount == 0) - return 0; - // Negative transfers will happen in the opposite direction - if (amount < 0) - { - int tempIndex = srcBucketIndex; - srcBucketIndex = destBucketIndex; - destBucketIndex = tempIndex; - amount = -amount; - } - synchronized (data) - { - if (amount > data[srcBucketIndex]) - amount = data[srcBucketIndex]; - if (amount <= 0) - return 0; - data[srcBucketIndex] -= amount; - data[destBucketIndex] += amount; - return amount; - } - } - - public int[] getBuckets() - { - synchronized (data) - { return data.clone(); } - } - } - - public static int getTotal(int[] values) - { - int totalValue = 0; - for (int i = values.length - 1; i >= 0; i--) - totalValue += values[i]; - return totalValue; - } - - public static void main(String[] args) - { - final int NUM_BUCKETS = 10; - Random rnd = new Random(); - final int[] values = new int[NUM_BUCKETS]; - for (int i = 0; i < values.length; i++) - values[i] = rnd.nextInt(10); - System.out.println("Initial Array: " + getTotal(values) + " " + Arrays.toString(values)); - final Buckets buckets = new Buckets(values); - - new Thread(new Runnable() { - public void run() - { - Random r = new Random(); - while (true) - { - int srcBucketIndex = r.nextInt(NUM_BUCKETS); - int destBucketIndex = r.nextInt(NUM_BUCKETS); - int amount = (buckets.getBucket(srcBucketIndex) - buckets.getBucket(destBucketIndex)) >> 1; - if (amount != 0) - buckets.transfer(srcBucketIndex, destBucketIndex, amount); - } - } - } - ).start(); - - new Thread(new Runnable() { - public void run() - { - Random r = new Random(); - while (true) - { - int srcBucketIndex = r.nextInt(NUM_BUCKETS); - int destBucketIndex = r.nextInt(NUM_BUCKETS); - int srcBucketAmount = buckets.getBucket(srcBucketIndex); - int destBucketAmount = buckets.getBucket(destBucketIndex); - int amount = r.nextInt(srcBucketAmount + destBucketAmount + 1) - destBucketAmount; - if (amount != 0) - buckets.transfer(srcBucketIndex, destBucketIndex, amount); - } - } - } - ).start(); - - while (true) - { - long nextPrintTime = System.currentTimeMillis() + 3000; - long curTime; - while ((curTime = System.currentTimeMillis()) < nextPrintTime) - { - try - { Thread.sleep(nextPrintTime - curTime); } - catch (InterruptedException e) - { } - } - int[] bucketValues = buckets.getBuckets(); - System.out.println("Current values: " + getTotal(bucketValues) + " " + Arrays.toString(bucketValues)); - } - } -} diff --git a/Task/Averages-Arithmetic-mean/Clojure/averages-arithmetic-mean.clj b/Task/Averages-Arithmetic-mean/Clojure/averages-arithmetic-mean.clj deleted file mode 100644 index 158c58a5b0..0000000000 --- a/Task/Averages-Arithmetic-mean/Clojure/averages-arithmetic-mean.clj +++ /dev/null @@ -1,6 +0,0 @@ -(defn mean [sq] - (let [length (count sq)] - (if (zero? length) - 0 - (/ (reduce + sq) length))) -) diff --git a/Task/Averages-Mean-angle/Go/averages-mean-angle.go b/Task/Averages-Mean-angle/Go/averages-mean-angle.go deleted file mode 100644 index d058dd06b0..0000000000 --- a/Task/Averages-Mean-angle/Go/averages-mean-angle.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "fmt" - "math" - "math/cmplx" -) - -func deg2rad(d float64) float64 { return d * math.Pi / 180 } -func rad2deg(r float64) float64 { return r * 180 / math.Pi } - -func mean_angle(deg []float64) float64 { - sum := 0i - for _, x := range deg { sum += cmplx.Rect(1, deg2rad(x)) } - return rad2deg(cmplx.Phase(sum)) -} - -func main() { - for _, angles := range [][]float64 {{350, 10}, {90, 180, 270, 360}, {10, 20, 30}} { - fmt.Printf("The mean angle of %v is: %f degrees\n", angles, mean_angle(angles)) - } -} diff --git a/Task/Averages-Median/Perl-6/averages-median.pl6 b/Task/Averages-Median/Perl-6/averages-median.pl6 deleted file mode 100644 index 91de232a45..0000000000 --- a/Task/Averages-Median/Perl-6/averages-median.pl6 +++ /dev/null @@ -1,4 +0,0 @@ -sub median { - my @a = sort @_; - return (@a[@a.end / 2] + @a[@a / 2]) / 2; -} diff --git a/Task/Balanced-brackets/Scala/balanced-brackets.scala b/Task/Balanced-brackets/Scala/balanced-brackets.scala deleted file mode 100644 index 9a94614921..0000000000 --- a/Task/Balanced-brackets/Scala/balanced-brackets.scala +++ /dev/null @@ -1,36 +0,0 @@ -import scala.collection.mutable.ListBuffer -import scala.util.Random - -object BalancedBrackets extends App { - - val random = new Random() - def generateRandom: List[String] = { - import scala.util.Random._ - val shuffleIt: Int => String = i => shuffle(("["*i+"]"*i).toList).foldLeft("")(_+_) - (1 to 20).map(i=>(random.nextDouble*100).toInt).filter(_>2).map(shuffleIt(_)).toList - } - - def generate(n: Int): List[String] = { - val base = "["*n+"]"*n - var lb = ListBuffer[String]() - base.permutations.foreach(s=>lb+=s) - lb.toList.sorted - } - - def checkBalance(brackets: String):Boolean = { - def balI(brackets: String, depth: Int):Boolean = { - if (brackets == "") depth == 0 - else brackets(0) match { - case '[' => ((brackets.size > 1) && balI(brackets.substring(1), depth + 1)) - case ']' => (depth > 0) && ((brackets.size == 1) || balI(brackets.substring(1), depth -1)) - case _ => false - } - } - balI(brackets, 0) - } - - println("arbitrary random order:") - generateRandom.map(s=>Pair(s,checkBalance(s))).foreach(p=>println((if(p._2) "balanced: " else "unbalanced: ")+p._1)) - println("\n"+"check all permutations of given length:") - (1 to 5).map(generate(_)).flatten.map(s=>Pair(s,checkBalance(s))).foreach(p=>println((if(p._2) "balanced: " else "unbalanced: ")+p._1)) -} diff --git a/Task/Binary-digits/COBOL/binary-digits.cobol b/Task/Binary-digits/COBOL/binary-digits.cobol deleted file mode 100644 index 71ac0cebbc..0000000000 --- a/Task/Binary-digits/COBOL/binary-digits.cobol +++ /dev/null @@ -1,26 +0,0 @@ - IDENTIFICATION DIVISION. - PROGRAM-ID. SAMPLE. - - DATA DIVISION. - WORKING-STORAGE SECTION. - - 01 binary_number pic X(21). - 01 str pic X(21). - 01 binary_digit pic X. - 01 digit pic 9. - 01 n pic 9(7). - 01 nstr pic X(7). - - PROCEDURE DIVISION. - accept nstr - move nstr to n - perform until n equal 0 - divide n by 2 giving n remainder digit - move digit to binary_digit - string binary_digit DELIMITED BY SIZE - binary_number DELIMITED BY SPACE - into str - move str to binary_number - end-perform. - display binary_number - stop run. diff --git a/Task/Binary-digits/Ruby/binary-digits.rb b/Task/Binary-digits/Ruby/binary-digits.rb deleted file mode 100644 index 7259380f14..0000000000 --- a/Task/Binary-digits/Ruby/binary-digits.rb +++ /dev/null @@ -1,4 +0,0 @@ -16.times do |i| - puts '%b' % i - puts i.to_s 2 -end diff --git a/Task/Bitmap-B-zier-curves-Cubic/ALGOL-68/bitmap-b-zier-curves-cubic.alg b/Task/Bitmap-B-zier-curves-Cubic/ALGOL-68/bitmap-b-zier-curves-cubic.alg deleted file mode 100644 index 7a8ad63b2d..0000000000 --- a/Task/Bitmap-B-zier-curves-Cubic/ALGOL-68/bitmap-b-zier-curves-cubic.alg +++ /dev/null @@ -1,34 +0,0 @@ -PRAGMAT READ "Bresenhams_line_algorithm.a68" PRAGMAT; - -cubic bezier OF class image := - ( REF IMAGE picture, - POINT p1, p2, p3, p4, - PIXEL color, - UNION(INT, VOID) in n - )VOID: -BEGIN - INT n = (in n|(INT n):n|20); # default 20 # - [0:n]POINT points; - FOR i FROM LWB points TO UPB points DO - REAL t = i / n, - a = (1 - t)**3, - b = 3 * t * (1 - t)**2, - c = 3 * t**2 * (1 - t), - d = t**3; - x OF points [i] := ENTIER (0.5 + a * x OF p1 + b * x OF p2 + c * x OF p3 + d * x OF p4); - y OF points [i] := ENTIER (0.5 + a * y OF p1 + b * y OF p2 + c * y OF p3 + d * y OF p4) - OD; - FOR i FROM LWB points TO UPB points - 1 DO - (line OF class image)(picture, points (i), points (i + 1), color) - OD -END # cubic bezier #; - -# -The following test -# -IF test THEN - REF IMAGE x = INIT LOC[16,16]PIXEL; - (fill OF class image)(x, (white OF class image)); - (cubic bezier OF class image)(x, (16, 1), (1, 4), (3, 16), (15, 11), (black OF class image), EMPTY); - (print OF class image) (x) -FI diff --git a/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm.alg b/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm.alg deleted file mode 100644 index 44609d6819..0000000000 --- a/Task/Bitmap-Bresenhams-line-algorithm/ALGOL-68/bitmap-bresenhams-line-algorithm.alg +++ /dev/null @@ -1,53 +0,0 @@ -PRAGMAT READ "Basic_bitmap_storage.a68" PRAGMAT; - -line OF class image := (REF IMAGE picture, POINT start, stop, PIXEL color)VOID: -BEGIN - REAL dx = ABS (x OF stop - x OF start), - dy = ABS (y OF stop - y OF start); - REAL err; - POINT here := start, - step := (1, 1); - IF x OF start > x OF stop THEN - x OF step := -1 - FI; - IF y OF start > y OF stop THEN - y OF step := -1 - FI; - IF dx > dy THEN - err := dx / 2; - WHILE x OF here /= x OF stop DO - picture[x OF here, y OF here] := color; - err -:= dy; - IF err < 0 THEN - y OF here +:= y OF step; - err +:= dx - FI; - x OF here +:= x OF step - OD - ELSE - err := dy / 2; - WHILE y OF here /= y OF stop DO - picture[x OF here, y OF here] := color; - err -:= dx; - IF err < 0 THEN - x OF here +:= x OF step; - err +:= dy - FI; - y OF here +:= y OF step - OD - FI; - picture[x OF here, y OF here] := color # ensure dots to be drawn # -END # line #; - -### -The test program: -### -IF test THEN - REF IMAGE x = INIT LOC[1:16, 1:16]PIXEL; - (fill OF class image)(x, white OF class image); - (line OF class image)(x, ( 1, 8), ( 8,16), black OF class image); - (line OF class image)(x, ( 8,16), (16, 8), black OF class image); - (line OF class image)(x, (16, 8), ( 8, 1), black OF class image); - (line OF class image)(x, ( 8, 1), ( 1, 8), black OF class image); - (print OF class image)(x) -FI diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Python/bitmap-bresenhams-line-algorithm.py b/Task/Bitmap-Bresenhams-line-algorithm/Python/bitmap-bresenhams-line-algorithm.py deleted file mode 100644 index 4c79cd1f0e..0000000000 --- a/Task/Bitmap-Bresenhams-line-algorithm/Python/bitmap-bresenhams-line-algorithm.py +++ /dev/null @@ -1,58 +0,0 @@ -def line(self, x0, y0, x1, y1): - "Bresenham's line algorithm" - dx = abs(x1 - x0) - dy = abs(y1 - y0) - x, y = x0, y0 - sx = -1 if x0 > x1 else 1 - sy = -1 if y0 > y1 else 1 - if dx > dy: - err = dx / 2.0 - while x != x1: - self.set(x, y) - err -= dy - if err < 0: - y += sy - err += dx - x += sx - else: - err = dy / 2.0 - while y != y1: - self.set(x, y) - err -= dx - if err < 0: - x += sx - err += dy - y += sy - self.set(x, y) -Bitmap.line = line - -bitmap = Bitmap(17,17) -for points in ((1,8,8,16),(8,16,16,8),(16,8,8,1),(8,1,1,8)): - bitmap.line(*points) -bitmap.chardisplay() - -''' -The origin, 0,0; is the lower left, with x increasing to the right, -and Y increasing upwards. - -The chardisplay above produces the following output : -+-----------------+ -| @ | -| @ @ | -| @ @ | -| @ @ | -| @ @ | -| @ @ | -| @ @ | -| @ @ | -| @ @| -| @ @ | -| @ @ | -| @ @@ | -| @ @ | -| @ @ | -| @ @ | -| @ | -| | -+-----------------+ -''' diff --git a/Task/Bitmap-Midpoint-circle-algorithm/ALGOL-68/bitmap-midpoint-circle-algorithm.alg b/Task/Bitmap-Midpoint-circle-algorithm/ALGOL-68/bitmap-midpoint-circle-algorithm.alg deleted file mode 100644 index e1702ecccf..0000000000 --- a/Task/Bitmap-Midpoint-circle-algorithm/ALGOL-68/bitmap-midpoint-circle-algorithm.alg +++ /dev/null @@ -1,46 +0,0 @@ -PRAGMAT READ "Basic_bitmap_storage.a68" PRAGMAT; - -circle OF class image := - ( REF IMAGE picture, - POINT center, - INT radius, - PIXEL color - )VOID: -BEGIN - INT f := 1 - radius, - POINT ddf := (0, -2 * radius), - df := (0, radius); - picture [x OF center, y OF center + radius] := - picture [x OF center, y OF center - radius] := - picture [x OF center + radius, y OF center] := - picture [x OF center - radius, y OF center] := color; - WHILE x OF df < y OF df DO - IF f >= 0 THEN - y OF df -:= 1; - y OF ddf +:= 2; - f +:= y OF ddf - FI; - x OF df +:= 1; - x OF ddf +:= 2; - f +:= x OF ddf + 1; - picture [x OF center + x OF df, y OF center + y OF df] := - picture [x OF center - x OF df, y OF center + y OF df] := - picture [x OF center + x OF df, y OF center - y OF df] := - picture [x OF center - x OF df, y OF center - y OF df] := - picture [x OF center + y OF df, y OF center + x OF df] := - picture [x OF center - y OF df, y OF center + x OF df] := - picture [x OF center + y OF df, y OF center - x OF df] := - picture [x OF center - y OF df, y OF center - x OF df] := color - OD -END # circle #; - -# -The following illustrates use: -# - -IF test THEN - REF IMAGE x = INIT LOC [1:16, 1:16] PIXEL; - (fill OF class image)(x, (white OF class image)); - (circle OF class image)(x, (8, 8), 5, (black OF class image)); - (print OF class image)(x) -FI diff --git a/Task/Bitmap/ALGOL-68/bitmap.alg b/Task/Bitmap/ALGOL-68/bitmap.alg deleted file mode 100644 index 63e56e7f21..0000000000 --- a/Task/Bitmap/ALGOL-68/bitmap.alg +++ /dev/null @@ -1,54 +0,0 @@ -MODE PIXEL = STRUCT(#SHORT# BITS red,green,blue); -MODE POINT = STRUCT(INT x,y); - -MODE IMAGE = [0,0]PIXEL; # instance attributes # - -MODE CLASSIMAGE = STRUCT ( # class attributes # - PIXEL black, red, green, blue, white, - PROC (REF IMAGE)REF IMAGE init, - PROC (REF IMAGE, PIXEL)VOID fill, - PROC (REF IMAGE)VOID print, -# virtual: # - REF PROC (REF IMAGE, POINT, POINT, PIXEL)VOID line, - REF PROC (REF IMAGE, POINT, INT, PIXEL)VOID circle, - REF PROC (REF IMAGE, POINT, POINT, POINT, POINT, PIXEL, UNION(INT, VOID))VOID cubic bezier -); - -CLASSIMAGE class image = ( - # black = # (#SHORTEN# 16r00, #SHORTEN# 16r00, #SHORTEN# 16r00), - # red = # (#SHORTEN# 16rff, #SHORTEN# 16r00, #SHORTEN# 16r00), - # green = # (#SHORTEN# 16r00, #SHORTEN# 16rff, #SHORTEN# 16r00), - # blue = # (#SHORTEN# 16r00, #SHORTEN# 16r00, #SHORTEN# 16rff), - # white = # (#SHORTEN# 16rff, #SHORTEN# 16rff, #SHORTEN# 16rff), - # PROC init = # (REF IMAGE self)REF IMAGE: - BEGIN - (fill OF class image)(self, black OF class image); - self - END, - - # PROC fill = # (REF IMAGE self, PIXEL color)VOID: - FOR x FROM 1 LWB self TO 1 UPB self DO - FOR y FROM 2 LWB self TO 2 UPB self DO - self[x,y] := color - OD - OD, - # PROC print = # (REF IMAGE self)VOID: - printf(($n(UPB self)(3(16r2d))l$, self)), -# virtual: # - # REF PROC line = # LOC PROC (REF IMAGE, POINT, POINT, PIXEL)VOID, - # REF PROC circle = # LOC PROC (REF IMAGE, POINT, INT, PIXEL)VOID, - # REF PROC cubic bezier = # LOC PROC (REF IMAGE, POINT, POINT, POINT, POINT, PIXEL, UNION(INT, VOID))VOID -); - -OP CLASSOF = (IMAGE image)CLASSIMAGE: class image; -OP INIT = (REF IMAGE image)REF IMAGE: (init OF (CLASSOF image))(image); - -BOOL test = TRUE; -IF test THEN -### -The test program -### - REF IMAGE x := INIT LOC[1:16, 1:16]PIXEL; - (fill OF class image) (x, white OF class image); - (print OF class image) (x) -FI diff --git a/Task/Boolean-values/Julia/boolean-values.julia b/Task/Boolean-values/Julia/boolean-values.julia deleted file mode 100644 index 7649afa690..0000000000 --- a/Task/Boolean-values/Julia/boolean-values.julia +++ /dev/null @@ -1,4 +0,0 @@ -#Boolean and conditional expressions only accept 'true' or 'false' - -#Convert a number or numeric array to boolean -bool(x) diff --git a/Task/Bulls-and-cows/Julia/bulls-and-cows.julia b/Task/Bulls-and-cows/Julia/bulls-and-cows.julia deleted file mode 100644 index bc1a5add6f..0000000000 --- a/Task/Bulls-and-cows/Julia/bulls-and-cows.julia +++ /dev/null @@ -1,32 +0,0 @@ -function cowsbulls() - print("Welcome to Cows & Bulls! I've picked a number with unique digits between 1 and 9, go ahead and type your guess.\n - You get one bull for every right number in the right position.\n - You get one cow for every right number, but in the wrong position.\n - Enter 'n' to pick a new number and 'q' to quit.\n>") - function new_number() - s = [1:9] - n = "" - for i = 9:-1:6 - n *= string(delete!(s,rand(1:i))) - end - return n - end - answer = new_number() - while true - input = chomp(readline(STDIN)) - input == "q" && break - if input == "n" - answer = new_number() - print("\nI've picked a new number, go ahead and guess\n>") - continue - end - !ismatch(r"^[1-9]{4}$",input) && (print("Invalid guess: Please enter a 4-digit number\n>"); continue) - if input == answer - print("\nYou're right! Good guessing!\nEnter 'n' for a new number or 'q' to quit\n>") - else - bulls = sum(answer.data .== input.data) - cows = sum([answer[x] != input[x] && contains(input.data,answer[x]) for x = 1:4]) - print("\nNot quite! Your guess is worth:\n$bulls Bulls\n$cows Cows\nPlease guess again\n\n>") - end - end -end diff --git a/Task/Bulls-and-cows/Ruby/bulls-and-cows.rb b/Task/Bulls-and-cows/Ruby/bulls-and-cows.rb deleted file mode 100644 index f8bc7a4452..0000000000 --- a/Task/Bulls-and-cows/Ruby/bulls-and-cows.rb +++ /dev/null @@ -1,44 +0,0 @@ -def generate_word(len) - ([1, 2, 3, 4, 5, 6, 7, 8, 9].shuffle)[0,len].join("") -end - -def get_guess(len) - while true - print "Enter a guess: " - guess = gets.strip - err = case - when guess.match(/\D/) : "digits only" - when guess.length != len : "exactly #{len} digits" - when guess.split("").uniq.length != len: "digits must be unique " - else nil - end - break if err.nil? - puts "the word must be #{len} unique digits between 1 and 9 (#{err}). Try again." - end - guess -end - -def score(word, guess) - bulls = cows = 0 - guess.bytes.each_with_index do |byte, idx| - if word[idx] == byte - bulls += 1 - elsif word.include? byte - cows += 1 - end - end - [bulls, cows] -end - -srand -word_length = 4 -puts "I have chosen a number with #{word_length} unique digits from 1 to 9." -word = generate_word(word_length) -count = 0 -while true - guess = get_guess(word_length) - count += 1 - break if word == guess - puts "that guess has %d bulls and %d cows" % score(word, guess) -end -puts "you guessed correctly in #{count} tries." diff --git a/Task/Calendar/Scala/calendar.scala b/Task/Calendar/Scala/calendar.scala deleted file mode 100644 index 12f1dfb289..0000000000 --- a/Task/Calendar/Scala/calendar.scala +++ /dev/null @@ -1,203 +0,0 @@ -import java.util.TimeZone -import java.util.Locale -import java.util.Calendar -import java.util.GregorianCalendar - -object Helper { - def monthsMax(locale: Locale = Locale.getDefault): Int = { - val cal = Calendar.getInstance(locale) - cal.getMaximum(Calendar.MONTH) - } - - def numberOfMonths(locale: Locale = Locale.getDefault): Int = monthsMax(locale)+1 - - def namesOfMonths(year: Int, locale: Locale = Locale.getDefault): List[String] = { - val cal = Calendar.getInstance(locale) - val f1: Int => String = i => { - cal.set(year,i,1) - cal.getDisplayName(Calendar.MONTH, Calendar.LONG, locale) - } - (0 to monthsMax(locale)) map f1 toList - } - - def jgt(cal: GregorianCalendar): Int = {cal.setTime(cal.getGregorianChange); cal.get(Calendar.YEAR)} - - def isJGT(year: Int, cal: GregorianCalendar) = year==jgt(cal) - - def offsets(year: Int, locale: Locale = Locale.getDefault): List[Int] = { - val cal = Calendar.getInstance(locale) - val months = cal.getMaximum(Calendar.MONTH) - val f1: Int => Int = i => { - cal.set(year,i,1) - cal.get(Calendar.DAY_OF_WEEK) - } - ((0 to months) map f1 toList) map {i=>if((i-2)<0) i+5 else i-2} - } - - def headerNameOfDays(locale: Locale = Locale.getDefault) = { - val cal = Calendar.getInstance(locale) - val mdow = cal.getDisplayNames(Calendar.DAY_OF_WEEK, Calendar.SHORT, locale) // map days of week - val it = mdow.keySet.iterator - import scala.collection.mutable.ListBuffer - val lb = new ListBuffer[String] - while (it.hasNext) lb+=it.next - val lpdow = lb.toList.map{k=>(mdow.get(k),k.substring(0,2))} // list pair days of week - (lpdow map {p=>if((p._1-2)<0) (p._1+5, p._2) else (p._1-2, p._2)} sortWith(_._1<_._1) map (_._2)).foldRight("")(_+" "+_) - } - -} - -object CalendarPrint extends App { - import Helper._ - - val tzd = TimeZone.getDefault - val locd = Locale.getDefault - - def printCalendar(year: Int, printerWidth: Int, loc: Locale, tz: TimeZone) = { - - def getCal: List[Triple[Int, Int, String]] = { - val cal = new GregorianCalendar(tz, loc) - - def getGregCal: List[Triple[Int, Int, String]] = { - val month = 0 - val day = 1 - cal.set(year,month,day) - val f1: Int => Triple[Int, Int, Int] = i => { - val cal = Calendar.getInstance(tz, loc) - cal.set(year,i,1) - val minday = cal.getActualMinimum(Calendar.DAY_OF_MONTH) - val maxday = cal.getActualMaximum(Calendar.DAY_OF_MONTH) - (i, minday, maxday) - } - val limits = (0 to monthsMax(loc)) map f1 - val f2: (Int, Int, Int) => String = (year, month, day) => { - val cal = Calendar.getInstance(tz, loc) - cal.set(year,month,day) - cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, loc) - } - val calend = for { - i <- 0 to monthsMax(loc) - j <- limits(i)._2 to limits(i)._3 - val dow = f2(year, i, j) - } yield (i, j, dow) - if (isJGT(year, new GregorianCalendar(tz, loc))) calend.filter{_._1!=9}.toList else calend.toList - } - - def getJGT: List[Triple[Int, Int, String]] = { - if (!isJGT(year, new GregorianCalendar(tz, loc))) return Nil - - val cal = new GregorianCalendar(tz, loc) - cal.set(year,9,1) - var ldom = 0 - def it = new Iterator[Tuple3[Int,Int, String]]{ - def next={ - val res = (cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.GERMAN)) - ldom = res._2 - cal.roll(Calendar.DAY_OF_MONTH, true) - res - } - def hasNext = (cal.get(Calendar.DAY_OF_MONTH)>ldom) - } - it.toList - } - (getGregCal++getJGT).sortWith((s,t)=>s._1*100+s._2300) 300 else printerWidth - - def getFGW(msbs: Int,gsm: Int) = {val r=(pw-msbs*mw-gsm)/2; (r,gwf,r)} // fixed gap width - def getVGW(msbs: Int,gsm: Int) = pw-msbs*mw-gsm match { // variable gap width - case a if (a<2*gwm) => (a/2,gwm,a/2) - case b => {val x = (b+gsm)/(msbs+1); (x,x,x)} - } - - // months side by side, gaps sum minimum - val (msbs, gsm) = { - val (x, y) = {val c = if (pw/mw>12) 12 else pw/mw; if (c*mw+(c-1)*gwm<=pw) (c, c*gwm) else (c-1, (c-1)*gwm)} - val x1 = x match { - case 5 => 4 - case a if (a>6 && a<12) => 6 - case other => other - } - (x1, (x1-1)*gwm) - } - - // left margin, gap width, right margin - val (lm,gw,rm) = if (fgw) getFGW(msbs,gsm) else getVGW(msbs,gsm) - (pw,msbs,lm,gw,rm) - } - - val (pw,msbs,lm,gw,rm) = limits(printerWidth) - val monthsList = (0 to monthsMax(loc)).map{m=>calList.filter{_._1==m}}.toList - val nom = namesOfMonths(year,loc) - val offsetList = offsets(year,loc) - val hnod = headerNameOfDays(loc) - - val fsplit: List[(Int, Int, String)] => List[String] = list => { - val fap: Int => (Int, Int) = p => (p/7,p%7) - clear - for (i <- 0 until list.size) arr(fap(i+offsetList(list(i)._1))._1)(fap(i+offsetList(list(i)._1))._2)="%2d".format(list(i)._2) - //arr.toList.map(_.toList).map(_.foldLeft("")(_+" "+_)) - arr.toList.map(_.toList).map(_.foldRight("")(_+" "+_)) - } - val monthsRows = monthsList.map(fsplit) - - val center: (String, Int) => String = (s,l) => { - if (s.size>=l) s.substring(0,l) else - (" "*((l-s.size)/2)+s+" "*((l-s.size)/2)+" ").substring(0,l) - } - - println(center("[Snoopy Picture]",pw)) - println - println(center(""+year,pw)) - println - - val ul = numberOfMonths(loc) - val rowblocks = (1 to ul/msbs).map{i=> - (0 to 5).map{j=> - val lb = new scala.collection.mutable.ListBuffer[String] - val k = (i-1)*msbs - (k to k+msbs-1).map{l=> - lb+=monthsRows(l)(j) - } - lb.toList - }.toList - }.toList - - val mheaders = (1 to ul/msbs).map{i=>(0 to msbs-1).map{j=>center(nom(j+(i-1)*msbs),20)}.toList}.toList - val dowheaders = (1 to ul/msbs).map{i=>(0 to msbs-1).map{j=>center(hnod,20)}.toList}.toList - - (1 to 12/msbs).foreach{i=> - println(" "*lm+mheaders(i-1).foldRight("")(_+" "*gw+_)) - println(" "*lm+dowheaders(i-1).foldRight("")(_+" "*gw+_)) - rowblocks(i-1).foreach{xs=>println(" "*lm+xs.foldRight("")(_+" "*(gw-1)+_))} - println - } - - } - - val calList = getCal - printCal(calList) - - } - - def printGregCal(year: Int = 1969, pw: Int = 80, JGT: Boolean = false, loc: Locale = Locale.getDefault, tz: TimeZone = TimeZone.getDefault) { - val _year = if (JGT==false) year else jgt(new GregorianCalendar(tz, loc)) - printCalendar(_year, pw, loc, tz) - } - - printGregCal() - printGregCal(JGT=true, loc=Locale.UK, pw=132, tz=TimeZone.getTimeZone("UK/London")) - -} diff --git a/Task/Call-a-function/REXX/call-a-function.rexx b/Task/Call-a-function/REXX/call-a-function.rexx deleted file mode 100644 index cd2968ce8b..0000000000 --- a/Task/Call-a-function/REXX/call-a-function.rexx +++ /dev/null @@ -1,137 +0,0 @@ -/*REXX program to demonstrate various methods of calling a REXX function*/ -/*┌────────────────────────────────────────────────────────────────────┐ - │ Calling a function that REQUIRES no arguments. │ - │ │ - │ In the REXX language, there is no way to require the caller to not │ - │ pass arguments, but the programmer can check if any arguments were │ - │ (or weren't) passed. │ - └────────────────────────────────────────────────────────────────────┘*/ -yr=yearFunc() -say 'year=' yr -exit - -yearFunc: procedure -if arg()\==0 then call sayErr "SomeFunc function won't accept arguments." -return left(date('Sorted'),3) -/*┌────────────────────────────────────────────────────────────────────┐ - │ Calling a function with a fixed number of arguments. │ - │ │ - │ I take this to mean that the function requires a fixed number of │ - │ arguments. As above, REXX doesn't enforce calling (or invoking) │ - │ a (any) function with a certain number of arguments, but the │ - │ programmer can check if the correct number of arguments have been │ - │ specified (or not). │ - └────────────────────────────────────────────────────────────────────┘*/ -ggg=FourFunc(12,abc,6+q,zz%2,'da 5th disagreement') -say 'ggg squared=' ggg**2 -exit - -FourFunc: procedure; parse arg a1,a2,a3; a4=arg(4) /*another way get a4*/ - -if arg()\==4 then do - call sayErr "FourFunc function requires 4 arguments," - call sayErr "but instead it found" arg() 'arguments.' - exit 13 - end -return a1+a2+a3+a4 -/*┌────────────────────────────────────────────────────────────────────┐ - │ Calling a function with optional arguments. │ - │ │ - │ Note that not passing an argument isn't the same as passing a null │ - │ argument (a REXX variable whose value is length zero). │ - └────────────────────────────────────────────────────────────────────┘*/ -x=12; w=x/2; y=x**2; z=x//7 /* z is x modulo seven.*/ -say 'sum of w, x, y, & z=' SumIt(w,x,y,,z) /*pass 5 args, 4th is null*/ -exit - -SumIt: procedure; sum=0 - - do j=1 for arg() - if arg(j,'E') then sum=sum+arg(j) /*the Jth arg may have been omitted*/ - end - -return sum -/*┌────────────────────────────────────────────────────────────────────┐ - │ Calling a function with a variable number of arguments. │ - │ │ - │ This situation isn't any different then the previous example. │ - │ It's up to the programmer to code how to utilize the arguments. │ - └────────────────────────────────────────────────────────────────────┘*/ -/*┌────────────────────────────────────────────────────────────────────┐ - │ Calling a function with named arguments. │ - │ │ - │ REXX allows almost anything to be passed, so the following is one │ - │ way this can be accomplished. │ - └────────────────────────────────────────────────────────────────────┘*/ -what=parserFunc('name=Luna',"gravity=.1654",'moon=yes') -say 'name=' common.name -gr=common.gr -say 'gravity=' gr -exit - -parseFunc: procedure expose common. - do j=1 for arg() - parse var arg(j) name '=' val - upper name - call value 'COMMON.'name,val - end -return arg() -/*┌────────────────────────────────────────────────────────────────────┐ - │ Calling a function in statement context. │ - │ │ - │ REXX allows functions to be called (invoked) two ways, the first │ - │ example (above) is calling a function in statement context. │ - └────────────────────────────────────────────────────────────────────┘*/ -/*┌────────────────────────────────────────────────────────────────────┐ - │ Calling a function in within an expression. │ - │ │ - │ This is a variant of the first example. │ - └────────────────────────────────────────────────────────────────────┘*/ -yr=yearFunc()+20 -say 'two decades from now, the year will be:' yr -exit -/*┌────────────────────────────────────────────────────────────────────┐ - │ Obtaining the return value of a function. │ - │ │ - │ There are two ways to get the (return) value of a function. │ - └────────────────────────────────────────────────────────────────────┘*/ -currYear=yearFunc() -say 'the current year is' currYear - -call yearFunc -say 'the current year is' result -/*┌────────────────────────────────────────────────────────────────────┐ - │ Distinguishing built-in functions and user-defined functions. │ - │ │ - │ One objective of the REXX language is to allow the user to use any │ - │ function (or subroutine) name whether or not there is a built-in │ - │ function with the same name (there isn't a penality for this). │ - └────────────────────────────────────────────────────────────────────┘*/ -qqq=date() /*number of real dates that Bob was on. */ -say "Bob's been out" qqq 'times.' -www='DATE'('USA') /*returns date in format mm/dd/yyy */ -exit /*any function in quotes is external. */ - -date: return 4 -/*┌────────────────────────────────────────────────────────────────────┐ - │ Distinguishing subroutines and functions. │ - │ │ - │ There is no programatic difference between subroutines and │ - │ functions if the subroutine returns a value (which effectively │ - │ makes it a function). REXX allows you to call a function as if │ - │ it were a subroutine. │ - └────────────────────────────────────────────────────────────────────┘*/ -/*┌────────────────────────────────────────────────────────────────────┐ - │ In REXX, all arguments are passed by value, never by name, but it │ - │ is possible to accomplish this if the variable's name is passed │ - │ and the subroutine/function could use the built-in-function VALUE │ - │ to retrieve the variable's value. │ - └────────────────────────────────────────────────────────────────────┘*/ -/*┌────────────────────────────────────────────────────────────────────┐ - │ In the REXX language, partial application is possible, depending │ - │ how partial application is defined; I prefer the 1st definition (as│ - │ (as per the "discussion" for "Partial Function Application" task: │ - │ 1. The "syntactic sugar" that allows one to write (some examples│ - │ are: map (f 7 9) [1..9] │ - │ or: map(f(7,_,9),{1,...,9}) │ - └────────────────────────────────────────────────────────────────────┘*/ diff --git a/Task/Check-Machin-like-formulas/Perl-6/check-machin-like-formulas.pl6 b/Task/Check-Machin-like-formulas/Perl-6/check-machin-like-formulas.pl6 deleted file mode 100644 index b59bc958e1..0000000000 --- a/Task/Check-Machin-like-formulas/Perl-6/check-machin-like-formulas.pl6 +++ /dev/null @@ -1,20 +0,0 @@ -use Test; -plan *; - -is tan(atan(1/2)+atan(1/3)), 1; -is tan(2*atan(1/3)+atan(1/7)), 1; -is tan(4*atan(1/5)-atan(1/239)), 1; -is tan(5*atan(1/7)+2*atan(3/79)), 1; -is tan(5*atan(29/278)+7*atan(3/79)), 1; -is tan(atan(1/2)+atan(1/5)+atan(1/8)), 1; -is tan(4*atan(1/5)-atan(1/70)+atan(1/99)), 1; -is tan(5*atan(1/7)+4*atan(1/53)+2*atan(1/4443)), 1; -is tan(6*atan(1/8)+2*atan(1/57)+atan(1/239)), 1; -is tan(8*atan(1/10)-atan(1/239)-4*atan(1/515)), 1; -is tan(12*atan(1/18)+8*atan(1/57)-5*atan(1/239)), 1; -is tan(16*atan(1/21)+3*atan(1/239)+4*atan(3/1042)), 1; -is tan(22*atan(1/28)+2*atan(1/443)-5*atan(1/1393)-10*atan(1/11018)), 1; -is tan(22*atan(1/38)+17*atan(7/601)+10*atan(7/8149)), 1; -is tan(44*atan(1/57)+7*atan(1/239)-12*atan(1/682)+24*atan(1/12943)), 1; -is tan(88*atan(1/172)+51*atan(1/239)+32*atan(1/682)+44*atan(1/5357)+68*atan(1/12943)), 1; -is tan(88*atan(1/172)+51*atan(1/239)+32*atan(1/682)+44*atan(1/5357)+68*atan(1/12944)), 1; diff --git a/Task/Combinations-with-repetitions/D/combinations-with-repetitions.d b/Task/Combinations-with-repetitions/D/combinations-with-repetitions.d deleted file mode 100644 index 3583ca7429..0000000000 --- a/Task/Combinations-with-repetitions/D/combinations-with-repetitions.d +++ /dev/null @@ -1,86 +0,0 @@ -import std.stdio, std.range; - -const struct CombRep { - immutable uint nt, nc; - private immutable ulong[] combVal; - - this(in uint numType, in uint numChoice) pure nothrow - in { - assert(0 < numType && numType + numChoice <= 64, - "Valid only for nt + nc <= 64 (ulong bit size)"); - } body { - nt = numType; - nc = numChoice; - if (nc == 0) - return; - ulong v = (1UL << (nt - 1)) - 1; - - // Init to smallest number that has nt-1 bit set - // a set bit is metaphored as a _type_ seperator. - immutable limit = v << nc; - - // Limit is the largest nt-1 bit set number that has nc - // zero-bit a zero-bit means a _choice_ between _type_ - // seperators. - while (v <= limit) { - combVal ~= v; - if (v == 0) - break; - // Get next nt-1 bit number. - immutable t = (v | (v - 1)) + 1; - v = t | ((((t & -t) / (v & -v)) >> 1) - 1); - } - } - - uint length() @property const pure nothrow { - return combVal.length; - } - - uint[] opIndex(in uint idx) const pure nothrow { - return val2set(combVal[idx]); - } - - int opApply(immutable int delegate(in ref uint[]) dg) { - foreach (immutable v; combVal) { - auto set = val2set(v); - if (dg(set)) - break; - } - return 1; - } - - private uint[] val2set(in ulong v) const pure nothrow { - // Convert bit pattern to selection set - immutable uint bitLimit = nt + nc - 1; - uint typeIdx = 0; - uint[] set; - foreach (immutable bitNum; 0 .. bitLimit) - if (v & (1 << (bitLimit - bitNum - 1))) - typeIdx++; - else - set ~= typeIdx; - return set; - } -} - -// For finite Random Access Range. -auto combRep(R)(R types, in uint numChoice) /*pure nothrow*/ -if (hasLength!R && isRandomAccessRange!R) { - ElementType!R[][] result; - - foreach (const s; CombRep(types.length, numChoice)) { - ElementType!R[] r; - foreach (immutable i; s) - r ~= types[i]; - result ~= r; - } - - return result; -} - -void main() { - foreach (const e; combRep(["iced", "jam", "plain"], 2)) - writefln("%-(%5s %)", e); - writeln("Ways to select 3 from 10 types is ", - CombRep(10, 3).length); -} diff --git a/Task/Combinations/ALGOL-68/combinations.alg b/Task/Combinations/ALGOL-68/combinations.alg deleted file mode 100644 index 76fd3e2eba..0000000000 --- a/Task/Combinations/ALGOL-68/combinations.alg +++ /dev/null @@ -1,54 +0,0 @@ -MODE DATA = INT; - -PRIO C = 7; - -# Calculate the number of combinations anticipated # -OP C = (INT n, k)INT: - CASE k + 1 IN - # case 0: # 1, - # case 1: # n - OUT (n - 1) C (k - 1) * n OVER k - ESAC; - -PROC combinations = (INT m, []DATA list)[,]DATA: ( - CASE m IN - # case 1: # ( # transpose list # - [UPB list,1]DATA out; - out[,1]:=list; - out - ) - OUT - [UPB list C m, m]DATA out; - INT index out := 1; - FOR i TO UPB list DO - DATA x = list[i]; - [,]DATA y = combinations(m - 1, list[i+1:]); - FOR suffix TO UPB y DO - out[index out,1 ] := x; - out[index out,2:] := y[suffix,]; - index out +:= 1 - OD - OD; - out - ESAC -); - -PRIO COMB = 7; -OP COMB = (INT n, k)[,]INT: ( - [k]DATA list; # create a list to recombine # - FOR i TO UPB list DO list[i]:=i OD; - combinations(n,list) -); - -INT m = 3; - -#IF formatted transput possible THEN# - FORMAT data repr = $d$; - FORMAT list repr = $"("n(m-1)(f(data repr)",")f(data repr)")"$; - printf ((list repr, 3 COMB 5, $l$)); -#ELSE# - [,]DATA result = 3 COMB 5; - FOR row TO UPB result DO - print ((result[row,], new line)) - OD -#FI# diff --git a/Task/Combinations/Perl-6/combinations.pl6 b/Task/Combinations/Perl-6/combinations.pl6 deleted file mode 100644 index d5b36fc438..0000000000 --- a/Task/Combinations/Perl-6/combinations.pl6 +++ /dev/null @@ -1,12 +0,0 @@ -proto combine (Int, @) {*} - -multi combine (0, @) { [] } -multi combine ($, []) { () } -multi combine ($n, [$head, *@tail]) { - gather { - take [$head, @$_] for combine($n-1, @tail); - take [ @$_ ] for combine($n , @tail); - } -} - -say combine(3, [^5]).perl; diff --git a/Task/Combinations/Scala/combinations.scala b/Task/Combinations/Scala/combinations.scala deleted file mode 100644 index 026a48997b..0000000000 --- a/Task/Combinations/Scala/combinations.scala +++ /dev/null @@ -1,8 +0,0 @@ -implicit def toComb(m: Int) = new AnyRef { - def comb(n: Int) = recurse(m, List.range(0, n)) - private def recurse(m: Int, l: List[Int]): List[List[Int]] = (m, l) match { - case (0, _) => List(Nil) - case (_, Nil) => Nil - case _ => (recurse(m - 1, l.tail) map (l.head :: _)) ::: recurse(m, l.tail) - } -} diff --git a/Task/Comments/COBOL/comments.cobol b/Task/Comments/COBOL/comments.cobol deleted file mode 100644 index e019391287..0000000000 --- a/Task/Comments/COBOL/comments.cobol +++ /dev/null @@ -1 +0,0 @@ - * an asterisk in 7th column comments the line out diff --git a/Task/Comments/M4/comments.m4 b/Task/Comments/M4/comments.m4 deleted file mode 100644 index 70f4a12a49..0000000000 --- a/Task/Comments/M4/comments.m4 +++ /dev/null @@ -1,6 +0,0 @@ -eval(2*3) # eval(2*3) "#" and text after it aren't processed but passed along -dnl this text completely disappears, including the new line -divert(-1) -Everything diverted to -1 is processed but the output is discarded. -A comment could take this form as long as no macro names are used. -divert diff --git a/Task/Concurrent-computing/C++/concurrent-computing.cpp b/Task/Concurrent-computing/C++/concurrent-computing.cpp deleted file mode 100644 index dad8ecbf6a..0000000000 --- a/Task/Concurrent-computing/C++/concurrent-computing.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include -#include // MSVC++ - -void a(void) { std::cout << "Eat\n"; } -void b(void) { std::cout << "At\n"; } -void c(void) { std::cout << "Joe's\n"; } - -int main() -{ - // function pointers - Concurrency::parallel_invoke(&a, &b, &c); - - // C++11 lambda functions - Concurrency::parallel_invoke( - []{ std::cout << "Enjoy\n"; }, - []{ std::cout << "Rosetta\n"; }, - []{ std::cout << "Code\n"; } - ); - return 0; -} diff --git a/Task/Concurrent-computing/Clojure/concurrent-computing.clj b/Task/Concurrent-computing/Clojure/concurrent-computing.clj deleted file mode 100644 index 3258076963..0000000000 --- a/Task/Concurrent-computing/Clojure/concurrent-computing.clj +++ /dev/null @@ -1,2 +0,0 @@ -(doseq [text ["Enjoy" "Rosetta" "Code"]] - (future (println text))) diff --git a/Task/Concurrent-computing/CoffeeScript/concurrent-computing.coffee b/Task/Concurrent-computing/CoffeeScript/concurrent-computing.coffee deleted file mode 100644 index b893a9ffd3..0000000000 --- a/Task/Concurrent-computing/CoffeeScript/concurrent-computing.coffee +++ /dev/null @@ -1,5 +0,0 @@ -exec = require('child_process').exec - -for word in ["Enjoy", "Rosetta", "Code"] - exec "echo #{word}", (err, stdout) -> - console.log stdout diff --git a/Task/Concurrent-computing/PARI-GP/concurrent-computing.pari b/Task/Concurrent-computing/PARI-GP/concurrent-computing.pari deleted file mode 100644 index 5bb4e57f62..0000000000 --- a/Task/Concurrent-computing/PARI-GP/concurrent-computing.pari +++ /dev/null @@ -1,17 +0,0 @@ -void -foo() -{ - if (pari_daemon()) { - // Original - if (pari_daemon()) { - // Original - pari_printf("Enjoy\n"); - } else { - // Daemon #2 - pari_printf("Code\n"); - } - } else { - // Daemon #1 - pari_printf("Rosetta\n"); - } -} diff --git a/Task/Conditional-structures/AutoHotkey/conditional-structures.ahk b/Task/Conditional-structures/AutoHotkey/conditional-structures.ahk deleted file mode 100644 index 774a878c74..0000000000 --- a/Task/Conditional-structures/AutoHotkey/conditional-structures.ahk +++ /dev/null @@ -1,19 +0,0 @@ -; if -x = 1 -If x - MsgBox, x is %x% -Else If x > 1 - MsgBox, x is %x% -Else - MsgBox, x is %x% - -; ternary if -x = 2 -y = 1 -var := x > y ? 2 : 3 -MsgBox, % var - -; while -While (A_Index < 3) { - MsgBox, %A_Index% is less than 3 -} diff --git a/Task/Conways-Game-of-Life/Java/conways-game-of-life.java b/Task/Conways-Game-of-Life/Java/conways-game-of-life.java deleted file mode 100644 index e5c820c75f..0000000000 --- a/Task/Conways-Game-of-Life/Java/conways-game-of-life.java +++ /dev/null @@ -1,91 +0,0 @@ -public class GameOfLife{ - public static void main(String[] args){ - String[] dish= { - "_#_", - "_#_", - "_#_",}; - int gens= 3; - for(int i= 0;i < gens;i++){ - System.out.println("Generation " + i + ":"); - print(dish); - dish= life(dish); - } - } - - public static String[] life(String[] dish){ - String[] newGen= new String[dish.length]; - for(int row= 0;row < dish.length;row++){//each row - newGen[row]= ""; - for(int i= 0;i < dish[row].length();i++){//each char in the row - String above= "";//neighbors above - String same= "";//neighbors in the same row - String below= "";//neighbors below - if(i == 0){//all the way on the left - //no one above if on the top row - //otherwise grab the neighbors from above - above= (row == 0) ? null : dish[row - 1].substring(i, - i + 2); - same= dish[row].substring(i + 1, i + 2); - //no one below if on the bottom row - //otherwise grab the neighbors from below - below= (row == dish.length - 1) ? null : dish[row + 1] - .substring(i, i + 2); - }else if(i == dish[row].length() - 1){//right - //no one above if on the top row - //otherwise grab the neighbors from above - above= (row == 0) ? null : dish[row - 1].substring(i - 1, - i + 1); - same= dish[row].substring(i - 1, i); - //no one below if on the bottom row - //otherwise grab the neighbors from below - below= (row == dish.length - 1) ? null : dish[row + 1] - .substring(i - 1, i + 1); - }else{//anywhere else - //no one above if on the top row - //otherwise grab the neighbors from above - above= (row == 0) ? null : dish[row - 1].substring(i - 1, - i + 2); - same= dish[row].substring(i - 1, i) - + dish[row].substring(i + 1, i + 2); - //no one below if on the bottom row - //otherwise grab the neighbors from below - below= (row == dish.length - 1) ? null : dish[row + 1] - .substring(i - 1, i + 2); - } - int neighbors= getNeighbors(above, same, below); - if(neighbors < 2 || neighbors > 3){ - newGen[row]+= "_";//<2 or >3 neighbors -> die - }else if(neighbors == 3){ - newGen[row]+= "#";//3 neighbors -> spawn/live - }else{ - newGen[row]+= dish[row].charAt(i);//2 neighbors -> stay - } - } - } - return newGen; - } - - public static int getNeighbors(String above, String same, String below){ - int ans= 0; - if(above != null){//no one above - for(char x: above.toCharArray()){//each neighbor from above - if(x == '#') ans++;//count it if someone is here - } - } - for(char x: same.toCharArray()){//two on either side - if(x == '#') ans++;//count it if someone is here - } - if(below != null){//no one below - for(char x: below.toCharArray()){//each neighbor below - if(x == '#') ans++;//count it if someone is here - } - } - return ans; - } - - public static void print(String[] dish){ - for(String s: dish){ - System.out.println(s); - } - } -} diff --git a/Task/Create-an-HTML-table/C++/create-an-html-table.cpp b/Task/Create-an-HTML-table/C++/create-an-html-table.cpp deleted file mode 100644 index cd19508d3c..0000000000 --- a/Task/Create-an-HTML-table/C++/create-an-html-table.cpp +++ /dev/null @@ -1,68 +0,0 @@ -#include -#include -#include -#include -#include -#include - -void makeGap( int gap , std::string & text ) { - for ( int i = 0 ; i < gap ; i++ ) - text.append( " " ) ; -} - -int main( ) { - boost::array chars = { 'X' , 'Y' , 'Z' } ; - int headgap = 3 ; - int bodygap = 3 ; - int tablegap = 6 ; - int rowgap = 9 ; - std::string tabletext( "\n" ) ; - makeGap( headgap , tabletext ) ; - tabletext += "\n" ; - makeGap( bodygap , tabletext ) ; - tabletext += "\n" ; - makeGap( tablegap , tabletext ) ; - tabletext += "\n" ; - makeGap( tablegap + 1 , tabletext ) ; - tabletext += "\n" ; - makeGap( tablegap, tabletext ) ; - tabletext += "" ; - for ( int i = 0 ; i < 3 ; i++ ) { - tabletext += "" ; - } - tabletext += "\n" ; - makeGap( tablegap + 1 , tabletext ) ; - tabletext += "" ; - makeGap( tablegap + 1 , tabletext ) ; - tabletext += "\n" ; - srand( time( 0 ) ) ; - for ( int row = 0 ; row < 5 ; row++ ) { - makeGap( rowgap , tabletext ) ; - std::ostringstream oss ; - tabletext += "" ; - } - tabletext += "\n" ; - } - makeGap( tablegap + 1 , tabletext ) ; - tabletext += "\n" ; - makeGap( tablegap , tabletext ) ; - tabletext += "
" ; - tabletext += *(chars.begin( ) + i ) ; - tabletext += "
" ; - oss << row ; - tabletext += oss.str( ) ; - for ( int col = 0 ; col < 3 ; col++ ) { - oss.str( "" ) ; - int randnumber = rand( ) % 10000 ; - oss << randnumber ; - tabletext += "" ; - tabletext.append( oss.str( ) ) ; - tabletext += "
\n" ; - makeGap( bodygap , tabletext ) ; - tabletext += "\n" ; - tabletext += "\n" ; - std::ofstream htmltable( "testtable.html" , std::ios::out | std::ios::trunc ) ; - htmltable << tabletext ; - htmltable.close( ) ; - return 0 ; -} diff --git a/Task/Day-of-the-week/Scala/day-of-the-week.scala b/Task/Day-of-the-week/Scala/day-of-the-week.scala deleted file mode 100644 index 82cc65dec0..0000000000 --- a/Task/Day-of-the-week/Scala/day-of-the-week.scala +++ /dev/null @@ -1,13 +0,0 @@ -import java.util.{Calendar, GregorianCalendar} -import Calendar._ - -object DayOfTheWeek { - - def main(args:Array[String]) { - for (year <- 2008 to 2121; - date <- Some(new GregorianCalendar(year, DECEMBER, 25)); - if date.get(DAY_OF_WEEK) == SUNDAY) { - println(year) - } - } -} diff --git a/Task/Deal-cards-for-FreeCell/C++/deal-cards-for-freecell.cpp b/Task/Deal-cards-for-FreeCell/C++/deal-cards-for-freecell.cpp deleted file mode 100644 index d49d13b962..0000000000 --- a/Task/Deal-cards-for-FreeCell/C++/deal-cards-for-freecell.cpp +++ /dev/null @@ -1,76 +0,0 @@ -#include -#include - -//-------------------------------------------------------------------------------------------------- -using namespace std; - -//-------------------------------------------------------------------------------------------------- -class fc_dealer -{ -public: - void deal( int game ) - { - _gn = game; - fillDeck(); - shuffle(); - display(); - } - -private: - void fillDeck() - { - int p = 0; - for( int c = 0; c < 13; c++ ) - for( int s = 0; s < 4; s++ ) - _cards[p++] = c | s << 4; - } - - void shuffle() - { - srand( _gn ); - int cc = 52, nc, lc; - while( cc ) - { - nc = rand() % cc; - lc = _cards[--cc]; - _cards[cc] = _cards[nc]; - _cards[nc] = lc; - } - } - - void display() - { - char* suit = "CDHS"; - char* symb = "A23456789TJQK"; - int z = 0; - cout << "GAME #" << _gn << endl << "=======================" << endl; - for( int c = 51; c >= 0; c-- ) - { - cout << symb[_cards[c] & 15] << suit[_cards[c] >> 4] << " "; - if( ++z >= 8 ) - { - cout << endl; - z = 0; - } - } - } - - int _cards[52], _gn; -}; -//-------------------------------------------------------------------------------------------------- -int main( int argc, char* argv[] ) -{ - fc_dealer dealer; - int gn; - while( true ) - { - cout << endl << "Game number please ( 0 to QUIT ): "; cin >> gn; - if( !gn ) break; - - system( "cls" ); - dealer.deal( gn ); - cout << endl << endl; - } - return 0; -} -//-------------------------------------------------------------------------------------------------- diff --git a/Task/Delegates/Objective-C/delegates.m b/Task/Delegates/Objective-C/delegates.m deleted file mode 100644 index 38d53e37d5..0000000000 --- a/Task/Delegates/Objective-C/delegates.m +++ /dev/null @@ -1,76 +0,0 @@ -#import - -@interface Delegator : NSObject { - - id delegate; -} - -- (id)delegate; -- (void)setDelegate:(id)obj; -- (NSString *)operation; - -@end - -@implementation Delegator - -- (id)delegate { - - return delegate; -} - -- (void)setDelegate:(id)obj { - - delegate = obj; // Weak reference -} - -- (NSString *)operation { - - if ([delegate respondsToSelector:@selector(thing)]) - return [delegate thing]; - - return @"default implementation"; -} - -@end - -// Any object may implement these -@interface NSObject (DelegatorDelegating) - -- (NSString *)thing; - -@end - -@interface Delegate : NSObject - -// Don't need to declare -thing because any NSObject has this method - -@end - -@implementation Delegate - -- (NSString *)thing { - - return @"delegate implementation"; -} - -@end - -// Example usage -// Memory management ignored for simplification -int main() { - - // Without a delegate: - Delegator *a = [[Delegator alloc] init]; - NSLog(@"%d\n", [[a operation] isEqualToString:@"default implementation"]); - - // With a delegate that does not implement thing: - [a setDelegate:@"A delegate may be any object"]; - NSLog(@"%d\n", [[a operation] isEqualToString:@"delegate implementation"]); - - // With a delegate that implements "thing": - Delegate *d = [[Delegate alloc] init]; - [a setDelegate:d]; - NSLog(@"%d\n", [[a operation] isEqualToString:@"delegate implementation"]); - - return 0; -} diff --git a/Task/Delete-a-file/COBOL/delete-a-file.cobol b/Task/Delete-a-file/COBOL/delete-a-file.cobol deleted file mode 100644 index 9f0db641dc..0000000000 --- a/Task/Delete-a-file/COBOL/delete-a-file.cobol +++ /dev/null @@ -1,11 +0,0 @@ - IDENTIFICATION DIVISION. - PROGRAM-ID. Delete-Files. - - PROCEDURE DIVISION. - CALL "CBL_DELETE_FILE" USING "input.txt" - CALL "CBL_DELETE_DIR" USING "docs" - CALL "CBL_DELETE_FILE" USING "/input.txt" - CALL "CBL_DELETE_DIR" USING "/docs" - - GOBACK - . diff --git a/Task/Determine-if-a-string-is-numeric/COBOL/determine-if-a-string-is-numeric.cobol b/Task/Determine-if-a-string-is-numeric/COBOL/determine-if-a-string-is-numeric.cobol deleted file mode 100644 index 78d7fb024e..0000000000 --- a/Task/Determine-if-a-string-is-numeric/COBOL/determine-if-a-string-is-numeric.cobol +++ /dev/null @@ -1,58 +0,0 @@ - IDENTIFICATION DIVISION. - PROGRAM-ID. Is-Numeric. - - DATA DIVISION. - WORKING-STORAGE SECTION. - 01 Numeric-Chars PIC X(10) VALUE "0123456789". - - 01 Success CONSTANT 0. - *> By convention, a non-zero value is used to signify failure - 01 Failure CONSTANT 128. - - LOCAL-STORAGE SECTION. - 01 I PIC 99. - - 01 Num-Decimal-Points PIC 99. - 01 Num-Valid-Chars PIC 99. - - LINKAGE SECTION. - 01 Str PIC X(30). - - PROCEDURE DIVISION USING BY VALUE Str. - - IF Str = SPACES - MOVE Failure TO Return-Code - - GOBACK - END-IF - - MOVE FUNCTION TRIM(Str) TO Str - - INSPECT Str TALLYING Num-Decimal-Points FOR ALL "." - IF Num-Decimal-Points > 1 - MOVE Failure TO Return-Code - - GOBACK - ELSE - ADD Num-Decimal-Points TO Num-Valid-Chars - END-IF - - IF Str (1:1) = "-" OR "+" - ADD 1 TO Num-Valid-Chars - END-IF - - PERFORM VARYING I FROM 1 BY 1 UNTIL I > 10 - INSPECT Str TALLYING Num-Valid-Chars - FOR ALL Numeric-Chars (I:1) BEFORE SPACE - END-PERFORM - - INSPECT Str TALLYING Num-Valid-Chars FOR TRAILING SPACES - - IF Num-Valid-Chars = FUNCTION LENGTH(Str) - MOVE Success TO Return-Code - ELSE - MOVE Failure TO Return-Code - END-IF - - GOBACK - . diff --git a/Task/Determine-if-a-string-is-numeric/Racket/determine-if-a-string-is-numeric.rkt b/Task/Determine-if-a-string-is-numeric/Racket/determine-if-a-string-is-numeric.rkt deleted file mode 100644 index 1940c6d912..0000000000 --- a/Task/Determine-if-a-string-is-numeric/Racket/determine-if-a-string-is-numeric.rkt +++ /dev/null @@ -1 +0,0 @@ -(define (string-numeric? s) (number? (string->number s))) diff --git a/Task/Dinesmans-multiple-dwelling-problem/Mathematica/dinesmans-multiple-dwelling-problem.math b/Task/Dinesmans-multiple-dwelling-problem/Mathematica/dinesmans-multiple-dwelling-problem.math deleted file mode 100644 index ab3b32e9bb..0000000000 --- a/Task/Dinesmans-multiple-dwelling-problem/Mathematica/dinesmans-multiple-dwelling-problem.math +++ /dev/null @@ -1,15 +0,0 @@ -floor[x_,y_]:=Flatten[Position[y,x]][[1]] -Select[Permutations[{"Baker","Cooper","Fletcher","Miller","Smith"}], - ( floor["Baker",#] < 5 ) -&&( Abs[floor["Fletcher",#] - floor["Cooper",#]] > 1 ) -&&( Abs[floor["Fletcher",#] - floor["Smith",#]] > 1 ) -&&( 1 < floor["Cooper",#] < floor["Miller",#] ) -&&( 1 < floor["Fletcher",#] < 5 ) -&] [[1]] //Reverse //Column - --> -Miller -Fletcher -Baker -Cooper -Smith diff --git a/Task/Dinesmans-multiple-dwelling-problem/Ruby/dinesmans-multiple-dwelling-problem.rb b/Task/Dinesmans-multiple-dwelling-problem/Ruby/dinesmans-multiple-dwelling-problem.rb deleted file mode 100644 index 2ab9c3631d..0000000000 --- a/Task/Dinesmans-multiple-dwelling-problem/Ruby/dinesmans-multiple-dwelling-problem.rb +++ /dev/null @@ -1,38 +0,0 @@ -def dinesman(floors, names, criteria) - # the "bindVars" method returns a context where the "name" variables are bound to values - eval " - def bindVars(#{names.map {|n| n.downcase}.join ','}) - return binding - end - " - expression = criteria.map {|c| "(#{c.downcase})"}.join " and " - - floors.permutation.each do |perm| - b = bindVars *perm - return b if b.eval(expression) - end - nil -end - -floors = (1..5).to_a -names = %w(Baker Cooper Fletcher Miller Smith) -criteria = [ - "Baker != 5", - "Cooper != 1", - "Fletcher != 1", - "Fletcher != 5", - "Miller > Cooper", - "(Smith - Fletcher).abs != 1", - "(Fletcher - Cooper).abs != 1", -] - -b = dinesman(floors, names, criteria) - -if b.nil? - puts "no solution" -else - puts "Found a solution:" - len = names.map {|n| n.length}.max - residents = names.inject({}) {|r, n| r[b.eval(n.downcase)] = n; r} - floors.each {|f| puts " Floor #{f}: #{residents[f]}"} -end diff --git a/Task/Dining-philosophers/Haskell/dining-philosophers.hs b/Task/Dining-philosophers/Haskell/dining-philosophers.hs deleted file mode 100644 index 4950cb0480..0000000000 --- a/Task/Dining-philosophers/Haskell/dining-philosophers.hs +++ /dev/null @@ -1,65 +0,0 @@ -module Philosophers where - -import Control.Monad -import Control.Concurrent -import Control.Concurrent.STM -import System.Random - --- TMVars are transactional references. They can only be used in transactional actions. --- They are either empty or contain one value. Taking an empty reference fails and --- putting a value in a full reference fails. A transactional action only succeeds --- when all the component actions succeed, else it rolls back and retries until it --- succeeds. --- The Int is just for display purposes. -type Fork = TMVar Int - -newFork :: Int -> IO Fork -newFork i = newTMVarIO i - --- The basic transactional operations on forks -takeFork :: Fork -> STM Int -takeFork fork = takeTMVar fork - -releaseFork :: Int -> Fork -> STM () -releaseFork i fork = putTMVar fork i - -type Name = String - -runPhilosopher :: Name -> (Fork, Fork) -> IO () -runPhilosopher name (left, right) = forever $ do - putStrLn (name ++ " is hungry.") - - -- Run the transactional action atomically. - -- The type system ensures this is the only way to run transactional actions. - (leftNum, rightNum) <- atomically $ do - leftNum <- takeFork left - rightNum <- takeFork right - return (leftNum, rightNum) - - putStrLn (name ++ " got forks " ++ show leftNum ++ " and " ++ show rightNum ++ " and is now eating.") - delay <- randomRIO (1,10) - threadDelay (delay * 1000000) -- 1, 10 seconds. threadDelay uses nanoseconds. - putStrLn (name ++ " is done eating. Going back to thinking.") - - atomically $ do - releaseFork leftNum left - releaseFork rightNum right - - delay <- randomRIO (1, 10) - threadDelay (delay * 1000000) - -philosophers :: [String] -philosophers = ["Aristotle", "Kant", "Spinoza", "Marx", "Russel"] - -main = do - forks <- mapM newFork [1..5] - let namedPhilosophers = map runPhilosopher philosophers - forkPairs = zip forks (tail . cycle $ forks) - philosophersWithForks = zipWith ($) namedPhilosophers forkPairs - - putStrLn "Running the philosophers. Press enter to quit." - - mapM_ forkIO philosophersWithForks - - -- All threads exit when the main thread exits. - getLine diff --git a/Task/Discordian-date/Scala/discordian-date.scala b/Task/Discordian-date/Scala/discordian-date.scala deleted file mode 100644 index 589c675dd7..0000000000 --- a/Task/Discordian-date/Scala/discordian-date.scala +++ /dev/null @@ -1,19 +0,0 @@ -import java.util.{GregorianCalendar, Calendar} - -val DISCORDIAN_SEASONS=Array("Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath") -def ddate(year:Int, month:Int, day:Int):String={ - val date=new GregorianCalendar(year, month-1, day) - val dyear=year+1166 - - val isLeapYear=date.isLeapYear(year) - if(isLeapYear && month==2 && day==29) - return "St. Tib's Day "+dyear+" YOLD" - - var dayOfYear=date.get(Calendar.DAY_OF_YEAR) - if(isLeapYear && dayOfYear>=60) - dayOfYear-=1 // compensate for St. Tib's Day - - val dday=dayOfYear%73 - val season=dayOfYear/73 - "%s %d, %d YOLD".format(DISCORDIAN_SEASONS(season), dday, dyear) -} diff --git a/Task/Documentation/REXX/documentation.rexx b/Task/Documentation/REXX/documentation.rexx deleted file mode 100644 index 289d39e386..0000000000 --- a/Task/Documentation/REXX/documentation.rexx +++ /dev/null @@ -1,36 +0,0 @@ -/*REXX program to show how to display embedded documention in REXX code.*/ -parse arg doc -doc=space(doc) -if doc=='?' then call help /*show doc if arg is a single ? */ -/*════════════════════════regular═══════════════════════════════════════*/ -/*════════════════════════════════mainline══════════════════════════════*/ -/*═════════════════════════════════════════code═════════════════════════*/ -/*══════════════════════════════════════════════here.═══════════════════*/ -exit - -/*──────────────────────────────────HELP subroutine─────────────────────*/ -help: help=0; do j=1 for sourceline() - _=sourceline(j) - if _=='' then do; help=1; iterate; end - if _=='' then exit - if help then say _ - end /*j*/ -exit /*stick a fork in it, we're done.*/ - -/*──────────────────────────────────start of the in─line documentation. - -To use the YYYY program, enter: - - - YYYY numberOfItems - YYYY (with no args for the default) - YYYY ? (to see this documentation) - - -─── where: - -numberOfItems is the number of items to be processed. - -If no "numberOfItems" are entered, the default of 100 is used. - -────────────────────────────────────end of the in─line documentation. */ diff --git a/Task/Doubly-linked-list-Definition/ALGOL-68/doubly-linked-list-definition.alg b/Task/Doubly-linked-list-Definition/ALGOL-68/doubly-linked-list-definition.alg deleted file mode 100644 index 5f240d5464..0000000000 --- a/Task/Doubly-linked-list-Definition/ALGOL-68/doubly-linked-list-definition.alg +++ /dev/null @@ -1,113 +0,0 @@ -MODE DATA = STRING; # user defined data type # - -MODE MNODE = STRUCT ( - NODE pred, - succ, - DATA value -); - -MODE LIST = REF MNODE; -MODE NODE = REF MNODE; - -STRUCT ( - PROC LIST new list, - PROC (LIST)BOOL is empty, - PROC (LIST)NODE get head, - get tail, - PROC (LIST, NODE)NODE add tail, - add head, - PROC (LIST)NODE remove head, - remove tail, - PROC (LIST, NODE, NODE)NODE insert after, - PROC (LIST, NODE)NODE remove node -) class list; - -new list OF class list := LIST: ( - HEAP MNODE master link; - master link := (master link, master link, ~); - master link -); - -is empty OF class list := (LIST self)BOOL: - (LIST(pred OF self) :=: LIST(self)) AND (LIST(self) :=: LIST(succ OF self)); - -get head OF class list := (LIST self)NODE: - succ OF self; - -get tail OF class list := (LIST self)NODE: - pred OF self; - -add tail OF class list := (LIST self, NODE node)NODE: - (insert after OF class list)(self, pred OF self, node); - -add head OF class list := (LIST self, NODE node)NODE: - (insert after OF class list)(self, succ OF self, node); - -remove head OF class list := (LIST self)NODE: - (remove node OF class list)(self, succ OF self); - -remove tail OF class list := (LIST self)NODE: - (remove node OF class list)(self, pred OF self); - -insert after OF class list := (LIST self, NODE cursor, NODE node)NODE: ( - succ OF node := succ OF cursor; - pred OF node := cursor; - succ OF cursor := node; - pred OF succ OF node := node; - node -); - -remove node OF class list := (LIST self, NODE node)NODE: ( - succ OF pred OF node := succ OF node; - pred OF succ OF node := pred OF node; - succ OF node := pred OF node := NIL; # garbage collection hint # - node -); - -main: ( - - []DATA sample = ("Was", "it", "a", "cat", "I", "saw"); - - LIST list a := new list OF class list; - - NODE tmp; - - IF list a :/=: REF LIST(NIL) THEN # technically "list a" is never NIL # -# Add some data to a list # - FOR i TO UPB sample DO - tmp := HEAP MNODE; - IF tmp :/=: NODE(NIL) THEN # technically "tmp" is never NIL # - value OF tmp := sample[i]; - (add tail OF class list)(list a, tmp) - FI - OD; - -# Iterate throught the list forward # - NODE node := (get head OF class list)(list a); - print("Iterate orward: "); - WHILE node :/=: NODE(list a) DO - print((value OF node, " ")); - node := succ OF node - OD; - print(new line); - -# Iterate throught the list backward # - node := (get tail OF class list)(list a); - print("Iterate backward: "); - WHILE node :/=: NODE(list a) DO - print((value OF node, " ")); - node := pred OF node - OD; - print(new line); - -# Finally empty the list # - print("Empty from tail: "); - WHILE NOT (is empty OF class list)(list a) DO - tmp := (remove tail OF class list)(list a); - print((value OF tmp, " ")) - # sweep heap # - OD; - print(new line) - # sweep heap # - FI -) diff --git a/Task/Doubly-linked-list-Traversal/D/doubly-linked-list-traversal.d b/Task/Doubly-linked-list-Traversal/D/doubly-linked-list-traversal.d deleted file mode 100644 index d0114def0a..0000000000 --- a/Task/Doubly-linked-list-Traversal/D/doubly-linked-list-traversal.d +++ /dev/null @@ -1,42 +0,0 @@ -import std.stdio; - -struct Node(T) { - T data; - Node* prev, next; - - this(T data_, Node* prev_=null, Node* next_=null) { - data = data_; - prev = prev_; - next = next_; - } -} - -void prepend(T)(ref Node!(T)* head, T item) { - auto newNode = new Node!T(item, null, head); - if (head) - head.prev = newNode; - head = newNode; -} - -void main() { - Node!(string)* head; - prepend(head, "D"); - prepend(head, "C"); - prepend(head, "B"); - prepend(head, "A"); - - auto p = head; - auto last = p; - while (p) { - write(p.data, " "); - last = p; - p = p.next; - } - writeln(); - - while (last) { - write(last.data, " "); - last = last.prev; - } - writeln(); -} diff --git a/Task/Element-wise-operations/D/element-wise-operations.d b/Task/Element-wise-operations/D/element-wise-operations.d deleted file mode 100644 index 318f785e19..0000000000 --- a/Task/Element-wise-operations/D/element-wise-operations.d +++ /dev/null @@ -1,40 +0,0 @@ -import std.stdio, std.algorithm, std.conv, std.string, - std.typetuple, std.traits; - -T[][] elementwise(string op, T, U)(in T[][] A, in U B) -@safe pure /*nothrow*/ -if (isNumeric!U || (isArray!U && isArray!(ForeachType!U) && - isNumeric!(ForeachType!(ForeachType!U)))) { - static if (!isNumeric!U) - assert(A.length == B.length); - if (!A.length) - return null; - auto R = new typeof(return)(A.length, A[0].length); - - foreach (r, row; A) - static if (isNumeric!U) { - R[r][] = mixin("row[] " ~ op ~ "B"); - } else { - assert(row.length == B[r].length); - R[r][] = mixin("row[] " ~ op ~ "B[r][]"); - } - - return R; -} - -string matRep(T)(in T[][] m) /*@safe pure nothrow*/ { - return "[" ~ join(map!text(m), ",\n ") ~ "]"; -} - -void main() { - const matrix = [[3, 5, 7], - [1, 2, 3], - [2, 4, 6]]; - const scalar = 2; - - foreach (op; TypeTuple!("+", "-", "*", "/", "^^")) { - writeln(op, ":"); - writeln(matRep(elementwise!op(matrix, scalar)), "\n"); - writeln(matRep(elementwise!op(matrix, matrix)), "\n"); - } -} diff --git a/Task/Enforced-immutability/Seed7/enforced-immutability.seed7 b/Task/Enforced-immutability/Seed7/enforced-immutability.seed7 deleted file mode 100644 index b9ee7765cb..0000000000 --- a/Task/Enforced-immutability/Seed7/enforced-immutability.seed7 +++ /dev/null @@ -1,3 +0,0 @@ -const integer: foo is 42; -const string: bar is "bar"; -const blahtype: blah is blahvalue; diff --git a/Task/Entropy/Perl-6/entropy.pl6 b/Task/Entropy/Perl-6/entropy.pl6 deleted file mode 100644 index bf683fb2c3..0000000000 --- a/Task/Entropy/Perl-6/entropy.pl6 +++ /dev/null @@ -1,5 +0,0 @@ -sub entropy(@a) { - [+] map -> \p { p * -log p }, @a.bag.values »/» +@a; -} - -say log(2) R/ entropy '1223334444'.comb; diff --git a/Task/Entropy/Python/entropy.py b/Task/Entropy/Python/entropy.py deleted file mode 100644 index 8cba757d03..0000000000 --- a/Task/Entropy/Python/entropy.py +++ /dev/null @@ -1,34 +0,0 @@ -from __future__ import division -import math - -def hist(source): - hist = {}; l = 0; - for e in source: - l += 1 - if e not in hist: - hist[e] = 0 - hist[e] += 1 - return (l,hist) - -def entropy(hist,l): - elist = [] - for v in hist.values(): - c = v / l - elist.append(-c * math.log(c ,2)) - return sum(elist) - -def printHist(h): - flip = lambda (k,v) : (v,k) - h = sorted(h.iteritems(), key = flip) - print 'Sym\thi\tfi\tInf' - for (k,v) in h: - print '%s\t%f\t%f\t%f'%(k,v,v/l,-math.log(v/l, 2)) - - - -source = "1223334444" -(l,h) = hist(source); -print '.[Results].' -print 'Length',l -print 'Entropy:', entropy(h, l) -printHist(h) diff --git a/Task/Factorial/BASIC256/factorial.basic256 b/Task/Factorial/BASIC256/factorial.basic256 deleted file mode 100644 index f4a959798a..0000000000 --- a/Task/Factorial/BASIC256/factorial.basic256 +++ /dev/null @@ -1,8 +0,0 @@ -function factorial(n) - factorial = 1 - if n>0 then - for p=1 to n - factorial *= p - next p - end if -end function diff --git a/Task/Factorial/Julia/factorial.julia b/Task/Factorial/Julia/factorial.julia deleted file mode 100644 index efd40f8bec..0000000000 --- a/Task/Factorial/Julia/factorial.julia +++ /dev/null @@ -1,10 +0,0 @@ -function factorial(n::Integer) - if n < 0 - return zero(n) - end - f = one(n) - for i = 2:n - f *= i - end - return f -end diff --git a/Task/Factorial/Perl-6/factorial.pl6 b/Task/Factorial/Perl-6/factorial.pl6 deleted file mode 100644 index 7660390136..0000000000 --- a/Task/Factorial/Perl-6/factorial.pl6 +++ /dev/null @@ -1,3 +0,0 @@ -sub postfix: { [*] 1..$^n } - -say 5!; #prints 120 diff --git a/Task/Fibonacci-sequence/Julia/fibonacci-sequence.julia b/Task/Fibonacci-sequence/Julia/fibonacci-sequence.julia deleted file mode 100644 index e78d961c15..0000000000 --- a/Task/Fibonacci-sequence/Julia/fibonacci-sequence.julia +++ /dev/null @@ -1 +0,0 @@ -fib(n) = n < 2 ? n : fib(n-1) + fib(n-2) diff --git a/Task/File-size/REXX/file-size.rexx b/Task/File-size/REXX/file-size.rexx deleted file mode 100644 index 842fac6e63..0000000000 --- a/Task/File-size/REXX/file-size.rexx +++ /dev/null @@ -1,13 +0,0 @@ -/*REXX pgm to verify a file's size (by reading the lines) in CD & root. */ -parse arg iFID . /*let user specify the file ID. */ -if iFID=='' then iFID='FILESIZ.DAT' /*Not specified? Then use default*/ -say 'size of' iFID '=' filesize(iFID) /*current directory.*/ -say 'size of \..\'iFID '=' filesize('\..\'iFID) /* root directory.*/ -exit /*stick a fork in it, we're done.*/ - -/*──────────────────────────────────FILESIZE subroutine─────────────────*/ -filesize: parse arg f - do r=1 while lines(f)\==0 - call linein f - end /*r*/ -return r-1 diff --git a/Task/Filter/ActionScript/filter.as b/Task/Filter/ActionScript/filter.as deleted file mode 100644 index 5b4ce714c0..0000000000 --- a/Task/Filter/ActionScript/filter.as +++ /dev/null @@ -1,6 +0,0 @@ -var arr:Array = new Array(1, 2, 3, 4, 5); -var evens:Array = new Array(); -for (var i:int = 0; i < arr.length(); i++) { - if (arr[i] % 2 == 0) - evens.push(arr[i]); -} diff --git a/Task/Filter/PARI-GP/filter.pari b/Task/Filter/PARI-GP/filter.pari deleted file mode 100644 index 317ad2dd5f..0000000000 --- a/Task/Filter/PARI-GP/filter.pari +++ /dev/null @@ -1 +0,0 @@ -selecteven(v)=vecextract(v,1<<(#v\2*2+1)\3); diff --git a/Task/Find-common-directory-path/Java/find-common-directory-path.java b/Task/Find-common-directory-path/Java/find-common-directory-path.java deleted file mode 100644 index 6516f14a81..0000000000 --- a/Task/Find-common-directory-path/Java/find-common-directory-path.java +++ /dev/null @@ -1,39 +0,0 @@ -public class CommonPath { - public static String commonPath(String... paths){ - String commonPath = ""; - String[][] folders = new String[paths.length][]; - for(int i = 0; i < paths.length; i++){ - folders[i] = paths[i].split("/"); //split on file separator - } - for(int j = 0; j < folders[0].length; j++){ - String thisFolder = folders[0][j]; //grab the next folder name in the first path - boolean allMatched = true; //assume all have matched in case there are no more paths - for(int i = 1; i < folders.length && allMatched; i++){ //look at the other paths - if(folders[i].length < j){ //if there is no folder here - allMatched = false; //no match - break; //stop looking because we've gone as far as we can - } - //otherwise - allMatched &= folders[i][j].equals(thisFolder); //check if it matched - } - if(allMatched){ //if they all matched this folder name - commonPath += thisFolder + "/"; //add it to the answer - }else{//otherwise - break;//stop looking - } - } - return commonPath; - } - - public static void main(String[] args){ - String[] paths = { "/home/user1/tmp/coverage/test", - "/home/user1/tmp/covert/operator", - "/home/user1/tmp/coven/members"}; - System.out.println(commonPath(paths)); - - String[] paths2 = { "/hame/user1/tmp/coverage/test", - "/home/user1/tmp/covert/operator", - "/home/user1/tmp/coven/members"}; - System.out.println(commonPath(paths2)); - } -} diff --git a/Task/Find-the-missing-permutation/Clojure/find-the-missing-permutation.clj b/Task/Find-the-missing-permutation/Clojure/find-the-missing-permutation.clj deleted file mode 100644 index 6778cd92b5..0000000000 --- a/Task/Find-the-missing-permutation/Clojure/find-the-missing-permutation.clj +++ /dev/null @@ -1,6 +0,0 @@ -(use 'clojure.contrib.combinatorics) -(use 'clojure.set) - -(def given (apply hash-set (partition 4 5 "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB" ))) -(def s1 (apply hash-set (permutations "ABCD"))) -(def missing (difference s1 given)) diff --git a/Task/First-class-functions/Racket/first-class-functions.rkt b/Task/First-class-functions/Racket/first-class-functions.rkt deleted file mode 100644 index caca291c78..0000000000 --- a/Task/First-class-functions/Racket/first-class-functions.rkt +++ /dev/null @@ -1,10 +0,0 @@ -#lang racket - -(define (compose f g) (λ (x) (f (g x)))) -(define (cube x) (expt x 3)) -(define (cube-root x) (expt x (/ 1 3))) -(define funlist (list sin cos cube)) -(define ifunlist (list asin acos cube-root)) - -(for ([f funlist] [i ifunlist]) - (displayln ((compose i f) 0.5))) diff --git a/Task/Five-weekends/JavaScript/five-weekends.js b/Task/Five-weekends/JavaScript/five-weekends.js deleted file mode 100644 index 0aaac76650..0000000000 --- a/Task/Five-weekends/JavaScript/five-weekends.js +++ /dev/null @@ -1,45 +0,0 @@ -function startsOnFriday(month, year) -{ - // 0 is Sunday, 1 is Monday, ... 5 is Friday, 6 is Saturday - return new Date(year, month, 1).getDay() === 5; -} -function has31Days(month, year) -{ - return new Date(year, month, 31).getDate() === 31; -} -function checkMonths(year) -{ - var month, count = 0; - for (month = 0; month < 12; month += 1) - { - if (startsOnFriday(month, year) && has31Days(month, year)) - { - count += 1; - document.write(year + ' ' + month + '
'); - } - } - return count; -} -function fiveWeekends() -{ - var - startYear = 1900, - endYear = 2100, - year, - monthTotal = 0, - yearsWithoutFiveWeekends = [], - total = 0; - for (year = startYear; year <= endYear; year += 1) - { - monthTotal = checkMonths(year); - total += monthTotal; - // extra credit - if (monthTotal === 0) - yearsWithoutFiveWeekends.push(year); - } - document.write('Total number of months: ' + total + '
'); - document.write('
'); - document.write(yearsWithoutFiveWeekends + '
'); - document.write('Years with no five-weekend months: ' + yearsWithoutFiveWeekends.length + '
'); -} -fiveWeekends(); diff --git a/Task/FizzBuzz/Common-Lisp/fizzbuzz.lisp b/Task/FizzBuzz/Common-Lisp/fizzbuzz.lisp deleted file mode 100644 index ec1475db6f..0000000000 --- a/Task/FizzBuzz/Common-Lisp/fizzbuzz.lisp +++ /dev/null @@ -1,22 +0,0 @@ -;; Solution 1: -(defun fizzbuzz () - (loop for x from 1 to 100 do - (princ (cond ((zerop (mod x 15)) "FizzBuzz") - ((zerop (mod x 3)) "Fizz") - ((zerop (mod x 5)) "Buzz") - (t x))) - (terpri))) - -;; Solution 2: -(defun fizzbuzz () - (loop for x from 1 to 100 do - (format t "~&~{~A~}" - (or (append (when (zerop (mod x 3)) '("Fizz")) - (when (zerop (mod x 5)) '("Buzz"))) - (list x))))) - -;; Solution 3: -(defun fizzbuzz () - (loop for n from 1 to 100 - do (format t "~&~[~[FizzBuzz~:;Fizz~]~*~:;~[Buzz~*~:;~D~]~]~%" - (mod n 3) (mod n 5) n))) diff --git a/Task/FizzBuzz/Julia/fizzbuzz.julia b/Task/FizzBuzz/Julia/fizzbuzz.julia deleted file mode 100644 index e769a21619..0000000000 --- a/Task/FizzBuzz/Julia/fizzbuzz.julia +++ /dev/null @@ -1,11 +0,0 @@ -for i = 1:100 - if i % 15 == 0 - println("FizzBuzz") - elseif i % 3 == 0 - println("Fizz") - elseif i % 5 == 0 - println("Buzz") - else - println(i) - end -end diff --git a/Task/Flatten-a-list/Common-Lisp/flatten-a-list.lisp b/Task/Flatten-a-list/Common-Lisp/flatten-a-list.lisp deleted file mode 100644 index 70be5aee45..0000000000 --- a/Task/Flatten-a-list/Common-Lisp/flatten-a-list.lisp +++ /dev/null @@ -1,4 +0,0 @@ -(defun flatten (structure) - (cond ((null structure) nil) - ((atom structure) `(,structure)) - (t (mapcan #'flatten structure)))) diff --git a/Task/Flatten-a-list/Julia/flatten-a-list.julia b/Task/Flatten-a-list/Julia/flatten-a-list.julia deleted file mode 100644 index 5d423fde4b..0000000000 --- a/Task/Flatten-a-list/Julia/flatten-a-list.julia +++ /dev/null @@ -1,10 +0,0 @@ -julia> t = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] -8-element Int32 Array: - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 diff --git a/Task/Floyds-triangle/Julia/floyds-triangle.julia b/Task/Floyds-triangle/Julia/floyds-triangle.julia deleted file mode 100644 index b9c84241be..0000000000 --- a/Task/Floyds-triangle/Julia/floyds-triangle.julia +++ /dev/null @@ -1,6 +0,0 @@ -#floyd(n) creates an n-row floyd's triangle counting from 1 to (n/2+.5)*n -function floyd(n) - x = 1 - dig(x,line,n) = (while line < n; x+=line; line+= 1 end; return ndigits(x)+1) - for line = 1:n, i = 1:line; print(lpad(x,dig(x,line,n)," ")); x+=1; i==line && print("\n") end -end diff --git a/Task/Formatted-numeric-output/PL-I/formatted-numeric-output.pli b/Task/Formatted-numeric-output/PL-I/formatted-numeric-output.pli deleted file mode 100644 index f613c8e94e..0000000000 --- a/Task/Formatted-numeric-output/PL-I/formatted-numeric-output.pli +++ /dev/null @@ -1,3 +0,0 @@ -put edit (X) (p'999999.V999'); /* Western format. */ - -put edit (X) (p'999999,V999'); /* In European format. */ diff --git a/Task/Formatted-numeric-output/Raven/formatted-numeric-output.raven b/Task/Formatted-numeric-output/Raven/formatted-numeric-output.raven deleted file mode 100644 index 1865890577..0000000000 --- a/Task/Formatted-numeric-output/Raven/formatted-numeric-output.raven +++ /dev/null @@ -1,3 +0,0 @@ -7.125 "%09.3f" print - -00007.125 diff --git a/Task/Four-bit-adder/D/four-bit-adder.d b/Task/Four-bit-adder/D/four-bit-adder.d deleted file mode 100644 index 65dfb09955..0000000000 --- a/Task/Four-bit-adder/D/four-bit-adder.d +++ /dev/null @@ -1,67 +0,0 @@ -import std.stdio, std.traits; - -void fourBitsAdder(T)(in T a0, in T a1, in T a2, in T a3, - in T b0, in T b1, in T b2, in T b3, - out T o0, out T o1, - out T o2, out T o3, - out T overflow) pure nothrow { - - // A XOR using only NOT, AND and OR, as task requires - static T xor(in T x, in T y) pure nothrow { - return (~x & y) | (x & ~y); - } - - static void halfAdder(in T a, in T b, - out T s, out T c) pure nothrow { - s = xor(a, b); - // s = a ^ b; // a natural XOR in D - c = a & b; - } - - static void fullAdder(in T a, in T b, in T ic, - out T s, out T oc) pure nothrow { - T ps, pc, tc; - - halfAdder(/*input*/a, b, /*output*/ps, pc); - halfAdder(/*input*/ps, ic, /*output*/s, tc); - oc = tc | pc; - } - - T zero, tc0, tc1, tc2; - - fullAdder(/*input*/a0, b0, zero, /*output*/o0, tc0); - fullAdder(/*input*/a1, b1, tc0, /*output*/o1, tc1); - fullAdder(/*input*/a2, b2, tc1, /*output*/o2, tc2); - fullAdder(/*input*/a3, b3, tc2, /*output*/o3, overflow); -} - -void main() { - alias size_t T; - static assert(isUnsigned!T); - - enum T one = T.max, - zero = T.min, - a0 = zero, a1 = one, a2 = zero, a3 = zero, - b0 = zero, b1 = one, b2 = one, b3 = one; - T s0, s1, s2, s3, overflow; - - fourBitsAdder(/*input*/ a0, a1, a2, a3, - /*input*/ b0, b1, b2, b3, - /*output*/s0, s1, s2, s3, overflow); - - writefln(" a3 %032b", a3); - writefln(" a2 %032b", a2); - writefln(" a1 %032b", a1); - writefln(" a0 %032b", a0); - writefln(" +"); - writefln(" b3 %032b", b3); - writefln(" b2 %032b", b2); - writefln(" b1 %032b", b1); - writefln(" b0 %032b", b0); - writefln(" ="); - writefln(" s3 %032b", s3); - writefln(" s2 %032b", s2); - writefln(" s1 %032b", s1); - writefln(" s0 %032b", s0); - writefln("overflow %032b", overflow); -} diff --git a/Task/Fractal-tree/D/fractal-tree.d b/Task/Fractal-tree/D/fractal-tree.d deleted file mode 100644 index 3fda982d13..0000000000 --- a/Task/Fractal-tree/D/fractal-tree.d +++ /dev/null @@ -1,43 +0,0 @@ -import dfl.all; -import std.math; - -class FractalTree: Form { - - private const double DEG_TO_RAD = PI / 180.0; - - this() { - width = 600; - height = 500; - text = "Fractal Tree"; - backColor = Color(0xFF, 0xFF, 0xFF); - startPosition = FormStartPosition.CENTER_SCREEN; - formBorderStyle = FormBorderStyle.FIXED_DIALOG; - maximizeBox = false; - } - - private void drawTree(Graphics g, Pen p, int x1, int y1, double angle, int depth) { - if (depth == 0) return; - int x2 = x1 + cast(int) (cos(angle * DEG_TO_RAD) * depth * 10.0); - int y2 = y1 + cast(int) (sin(angle * DEG_TO_RAD) * depth * 10.0); - g.drawLine(p, x1, y1, x2, y2); - drawTree(g, p, x2, y2, angle - 20, depth - 1); - drawTree(g, p, x2, y2, angle + 20, depth - 1); - } - - protected override void onPaint(PaintEventArgs ea){ - super.onPaint(ea); - Pen p = new Pen(Color(0, 0xAA, 0)); - drawTree(ea.graphics, p, 300, 450, -90, 9); - } -} - -int main() { - int result = 0; - try { - Application.run(new FractalTree); - } catch(Object o) { - msgBox(o.toString(), "Fatal Error", MsgBoxButtons.OK, MsgBoxIcon.ERROR); - result = 1; - } - return result; -} diff --git a/Task/Function-definition/Julia/function-definition.julia b/Task/Function-definition/Julia/function-definition.julia deleted file mode 100644 index 21a2c8f154..0000000000 --- a/Task/Function-definition/Julia/function-definition.julia +++ /dev/null @@ -1,3 +0,0 @@ -function multiply(a::Number,b::Number) - return a*b -end diff --git a/Task/GUI-component-interaction/Java/gui-component-interaction.java b/Task/GUI-component-interaction/Java/gui-component-interaction.java deleted file mode 100644 index 643611a4fb..0000000000 --- a/Task/GUI-component-interaction/Java/gui-component-interaction.java +++ /dev/null @@ -1,93 +0,0 @@ -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; -import java.awt.event.KeyListener; - -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JTextField; - -public class Interact extends JFrame{ - final JTextField numberField; - final JButton incButton, randButton; - - public Interact(){ - //stop the GUI threads when the user hits the X button - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - - numberField = new JTextField(); - incButton = new JButton("Increment"); - randButton = new JButton("Random"); - - numberField.setText("0");//start at 0 - - //listen for button presses in the text field - numberField.addKeyListener(new KeyListener(){ - @Override - public void keyTyped(KeyEvent e) { - //if the entered character is not a digit - if(!Character.isDigit(e.getKeyChar())){ - //eat the event (i.e. stop it from being processed) - e.consume(); - } - } - @Override - public void keyReleased(KeyEvent e){} - @Override - public void keyPressed(KeyEvent e){} - }); - - //listen for button clicks on the increment button - incButton.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent e) { - String text = numberField.getText(); - if(text.isEmpty()){ - numberField.setText("1"); - }else{ - numberField.setText((Long.valueOf(text) + 1) + ""); - } - } - }); - - //listen for button clicks on the random button - randButton.addActionListener(new ActionListener(){ - @Override - public void actionPerformed(ActionEvent e) { - //show a dialog and if they answer "Yes" - if(JOptionPane.showConfirmDialog(null, "Are you sure?") == - JOptionPane.YES_OPTION){ - //set the text field text to a random positive long - numberField.setText(Long.toString((long)(Math.random() - * Long.MAX_VALUE))); - } - } - }); - - //arrange the components in a grid with 2 rows and 1 column - setLayout(new GridLayout(2, 1)); - - //a secondary panel for arranging both buttons in one grid space in the window - JPanel buttonPanel = new JPanel(); - - //the buttons are in a grid with 1 row and 2 columns - buttonPanel.setLayout(new GridLayout(1, 2)); - //add the buttons - buttonPanel.add(incButton); - buttonPanel.add(randButton); - - //put the number field on top of the buttons - add(numberField); - add(buttonPanel); - //size the window appropriately - pack(); - - } - - public static void main(String[] args){ - new Interact().setVisible(true); - } -} diff --git a/Task/Generic-swap/Delphi/generic-swap.delphi b/Task/Generic-swap/Delphi/generic-swap.delphi deleted file mode 100644 index b9e19f587b..0000000000 --- a/Task/Generic-swap/Delphi/generic-swap.delphi +++ /dev/null @@ -1,8 +0,0 @@ -procedure Swap_T(var a, b: T); -var - temp: T; -begin - temp := a; - a := b; - b := temp; -end; diff --git a/Task/Greatest-common-divisor/Rust/greatest-common-divisor.rust b/Task/Greatest-common-divisor/Rust/greatest-common-divisor.rust deleted file mode 100644 index 2a5c68483e..0000000000 --- a/Task/Greatest-common-divisor/Rust/greatest-common-divisor.rust +++ /dev/null @@ -1,6 +0,0 @@ -fn gcd(a: int,b: int) -> int { - match b { - 0 => return a, - _ => return gcd(b,(a%b)), - } -} diff --git a/Task/Greatest-subsequential-sum/D/greatest-subsequential-sum.d b/Task/Greatest-subsequential-sum/D/greatest-subsequential-sum.d deleted file mode 100644 index 898ef780ef..0000000000 --- a/Task/Greatest-subsequential-sum/D/greatest-subsequential-sum.d +++ /dev/null @@ -1,30 +0,0 @@ -import std.stdio; - -inout(T[]) maxSubseq(T)(inout T[] sequence) pure nothrow { - int maxSum, thisSum, i, start, end = -1; - - foreach (j, x; sequence) { - thisSum += x; - if (thisSum < 0) { - i = j + 1; - thisSum = 0; - } else if (thisSum > maxSum) { - maxSum = thisSum; - start = i; - end = j; - } - } - - if (start <= end && start >= 0 && end >= 0) - return sequence[start .. end + 1]; - else - return []; -} - -void main() { - const a1 = [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]; - writeln("Maximal subsequence: ", maxSubseq(a1)); - - const a2 = [-1, -2, -3, -5, -6, -2, -1, -4, -4, -2, -1]; - writeln("Maximal subsequence: ", maxSubseq(a2)); -} diff --git a/Task/Guess-the-number-With-feedback--player-/C/guess-the-number-with-feedback--player-.c b/Task/Guess-the-number-With-feedback--player-/C/guess-the-number-with-feedback--player-.c deleted file mode 100644 index 51b5237c56..0000000000 --- a/Task/Guess-the-number-With-feedback--player-/C/guess-the-number-with-feedback--player-.c +++ /dev/null @@ -1,30 +0,0 @@ -#include - -int main(){ - int bounds[ 2 ] = {1, 100}; - char input[ 2 ] = " "; - /* second char is for the newline from hitting [return] */ - int choice = (bounds[ 0 ] + bounds[ 1 ]) / 2; - /* using a binary search */ - - printf( "Choose a number between %d and %d.\n", bounds[ 0 ], bounds[ 1 ] ); - - do{ - switch( input[ 0 ] ){ - case 'H': - bounds[ 1 ] = choice; - break; - case 'L': - bounds[ 0 ] = choice; - break; - case 'Y': - printf( "\nAwwwright\n" ); - return 0; - } - choice = (bounds[ 0 ] + bounds[ 1 ]) / 2; - - printf( "Is the number %d? (Y/H/L) ", choice ); - }while( scanf( "%1s", input ) == 1 ); - - return 0; -} diff --git a/Task/Hailstone-sequence/REXX/hailstone-sequence.rexx b/Task/Hailstone-sequence/REXX/hailstone-sequence.rexx deleted file mode 100644 index 4fc351b0a0..0000000000 --- a/Task/Hailstone-sequence/REXX/hailstone-sequence.rexx +++ /dev/null @@ -1,24 +0,0 @@ -/*REXX pgm tests a number and a range for hailstone (Collatz) sequences.*/ -parse arg x .; if x=='' then x=27 /*get the optional first argument*/ -numeric digits 20 -$=hailstone(x) /*═════════════task 1════════════*/ -say x 'has a hailstone sequence of' #hs 'and starts with: ' subword($,1,4), - ' and ends with:' subword($,#hs-3) -say -w=0; do j=1 for 99999 /*═════════════task 2════════════*/ - call hailstone j /*compute the hailstone sequence.*/ - if #hs<=w then iterate /*Not big 'nuff? Then keep going.*/ - bigJ=j; w=#hs /*remember what # has biggest HS.*/ - end /*j*/ - -say '(between 1──►99,999) ' bigJ 'has the longest hailstone sequence:' w -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────HAILSTONE subroutine────────────────*/ -hailstone: procedure expose #hs; parse arg n 1 s /*N & S set to 1st arg*/ - - do #hs=1 while n\==1 /*loop while N isn't unity. */ - if n//2 then n=n*3+1 /*if N is odd, calc: 3*n +1 */ - else n=n%2 /* " " " even, perform fast ÷ */ - s=s n /*build a sequence list (append).*/ - end /*#hs*/ -return s diff --git a/Task/Happy-numbers/Julia/happy-numbers.julia b/Task/Happy-numbers/Julia/happy-numbers.julia deleted file mode 100644 index 11a7b8d456..0000000000 --- a/Task/Happy-numbers/Julia/happy-numbers.julia +++ /dev/null @@ -1,15 +0,0 @@ -function happy(x) - happy_ints = ref(Int) - int_try = 1 - while length(happy_ints) < x - n = int_try - past = ref(Int) - while n != 1 - n = sum([int(string(y))^2 for y in string(n)]) - contains(past,n) ? break : push!(past,n) - end - if n == 1 push!(happy_ints,int_try) end - int_try += 1 - end - return happy_ints -end diff --git a/Task/Happy-numbers/Perl/happy-numbers.pl b/Task/Happy-numbers/Perl/happy-numbers.pl deleted file mode 100644 index 00663c1605..0000000000 --- a/Task/Happy-numbers/Perl/happy-numbers.pl +++ /dev/null @@ -1,11 +0,0 @@ -use List::Util qw(sum); - -sub is_happy ($) - {for (my ($n, %seen) = shift ;; $n = sum map {$_**2} split //, $n) - {$n == 1 and return 1; - $seen{$n}++ and return 0;}} - -for (my ($n, $happy) = (1, 0) ; $happy < 8 ; ++$n) - {is_happy $n or next; - print "$n\n"; - ++$happy;} diff --git a/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series.rexx b/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series.rexx deleted file mode 100644 index 5c47fca6db..0000000000 --- a/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series.rexx +++ /dev/null @@ -1,24 +0,0 @@ -/*REXX program finds first X Niven numbers; also first Niven number > Y.*/ -parse arg X Y . /*get optional arguments: X Y */ -if X=='' then X=20 /*Not specified? Then use default*/ -if Y=='' then Y=1000 /*Not specified? Then use default*/ -#=0; $= /*Niven# count, Niven# list. */ - - do j=1 until #==X /*let's go Niven number hunting. */ - if j//sumDigs(j)\==0 then iterate /*Not a Niven number? Then skip.*/ - #=#+1; $=$ j /*bump Niven# count, add to list.*/ - end /*j*/ - -say 'first' X 'Niven numbers:' $ - - do t=1 /*let's go Niven number searching*/ - if t//sumDigs(t)\==0 then iterate /*Not a Niven number? Then skip.*/ - if t>Y then leave /*if too low, then keep searching*/ - end /*t*/ - -say 'first Niven number >' Y " is: " t -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────SUMDIGS subroutine──────────────────*/ -sumDigs: procedure; parse arg ?; sum = left(?,1) - do k=2 to length(?); sum = sum+substr(?,k,1); end /*k*/ -return sum diff --git a/Task/Harshad-or-Niven-series/Racket/harshad-or-niven-series.rkt b/Task/Harshad-or-Niven-series/Racket/harshad-or-niven-series.rkt deleted file mode 100644 index 1ca387eb89..0000000000 --- a/Task/Harshad-or-Niven-series/Racket/harshad-or-niven-series.rkt +++ /dev/null @@ -1,20 +0,0 @@ -#lang racket -(require math/number-theory) -(define (digital-sum n) - (let inner - ((n n) (s 0)) - (if (zero? n) s - (let-values ([(q r) (quotient/remainder n 10)]) - (inner q (+ s r)))))) - -(define (harshad-number? n) - (and (>= n 1) - (divides? (digital-sum n) n))) - -;; find 1st 20 Harshad numbers -(for ((i (in-range 1 (add1 20))) - (h (sequence-filter harshad-number? (in-naturals 1)))) - (printf "#~a ~a~%" i h)) - -;; find 1st Harshad number > 1000 -(displayln (for/first ((h (sequence-filter harshad-number? (in-naturals 1001)))) h)) diff --git a/Task/Haversine-formula/D/haversine-formula.d b/Task/Haversine-formula/D/haversine-formula.d deleted file mode 100644 index 35eb5849ee..0000000000 --- a/Task/Haversine-formula/D/haversine-formula.d +++ /dev/null @@ -1,24 +0,0 @@ -import std.stdio, std.math; - -real haversineDistance(in real dth1, in real dph1, - in real dth2, in real dph2) pure nothrow { - - enum real R = 6371; - enum real TO_RAD = PI / 180; - - alias imr = immutable(real); - imr ph1d = dph1 - dph2; - imr ph1 = ph1d * TO_RAD; - imr th1 = dth1 * TO_RAD; - imr th2 = dth2 * TO_RAD; - - imr dz = sin(th1) - sin(th2); - imr dx = cos(ph1) * cos(th1) - cos(th2); - imr dy = sin(ph1) * cos(th1); - return asin(sqrt(dx ^^ 2 + dy ^^ 2 + dz ^^ 2) / 2) * 2 * R; -} - -void main() { - writefln("Haversine distance: %.1f km", - haversineDistance(36.12, -86.67, 33.94, -118.4)); -} diff --git a/Task/Hello-world-Graphical/COBOL/hello-world-graphical.cobol b/Task/Hello-world-Graphical/COBOL/hello-world-graphical.cobol deleted file mode 100644 index 2f46c51e30..0000000000 --- a/Task/Hello-world-Graphical/COBOL/hello-world-graphical.cobol +++ /dev/null @@ -1,19 +0,0 @@ - program-id. ghello. - data division. - working-storage section. - 01 var pic x(1). - 01 lynz pic 9(3). - 01 colz pic 9(3). - 01 msg pic x(15) value "Goodbye, world!". - procedure division. - accept lynz from lines end-accept - divide lynz by 2 giving lynz. - accept colz from columns end-accept - divide colz by 2 giving colz. - subtract 7 from colz giving colz. - display msg - at line number lynz - column number colz - end-display - accept var end-accept - stop run. diff --git a/Task/Hello-world-Line-printer/JavaScript/hello-world-line-printer.js b/Task/Hello-world-Line-printer/JavaScript/hello-world-line-printer.js deleted file mode 100644 index 6a057e5a7c..0000000000 --- a/Task/Hello-world-Line-printer/JavaScript/hello-world-line-printer.js +++ /dev/null @@ -1,6 +0,0 @@ -// This example runs on Node.js -var fs = require('fs'); -// Assuming lp is at /dev/lp0 -var lp = fs.openSync('/dev/lp0', 'w'); -fs.writeSync(lp, 'Hello, world!\n'); -fs.close(lp); diff --git a/Task/Hello-world-Line-printer/Python/hello-world-line-printer.py b/Task/Hello-world-Line-printer/Python/hello-world-line-printer.py deleted file mode 100644 index 9a79134c9f..0000000000 --- a/Task/Hello-world-Line-printer/Python/hello-world-line-printer.py +++ /dev/null @@ -1,3 +0,0 @@ -lp = open("/dev/lp0") -lp.write("Hello World!/n") -lp.close() diff --git a/Task/Hello-world-Newline-omission/Icon/hello-world-newline-omission.icon b/Task/Hello-world-Newline-omission/Icon/hello-world-newline-omission.icon deleted file mode 100644 index 550278b160..0000000000 --- a/Task/Hello-world-Newline-omission/Icon/hello-world-newline-omission.icon +++ /dev/null @@ -1,3 +0,0 @@ -procedure main() - writes("Goodbye, World!") -end diff --git a/Task/Hello-world-Standard-error/MATLAB/hello-world-standard-error.m b/Task/Hello-world-Standard-error/MATLAB/hello-world-standard-error.m deleted file mode 100644 index 8153dc5b12..0000000000 --- a/Task/Hello-world-Standard-error/MATLAB/hello-world-standard-error.m +++ /dev/null @@ -1 +0,0 @@ -error 'Goodbye, World!' diff --git a/Task/Hello-world-Text/Lua/hello-world-text.lua b/Task/Hello-world-Text/Lua/hello-world-text.lua deleted file mode 100644 index a9f594ad30..0000000000 --- a/Task/Hello-world-Text/Lua/hello-world-text.lua +++ /dev/null @@ -1 +0,0 @@ -print "Goodbye, World!" diff --git a/Task/Hello-world-Text/SNUSP/hello-world-text.snusp b/Task/Hello-world-Text/SNUSP/hello-world-text.snusp deleted file mode 100644 index 50a3619b42..0000000000 --- a/Task/Hello-world-Text/SNUSP/hello-world-text.snusp +++ /dev/null @@ -1,4 +0,0 @@ -@\G.@\o.o.@\d.--b.@\y.@\e.>@\comma.@\.<-@\W.+@\o.+++r.------l.@\d.>+.! # - | | \@------|# | \@@+@@++|+++#- \\ - - | \@@@@=+++++# | \===--------!\===!\-----|-------#-------/ - \@@+@@@+++++# \!#+++++++++++++++++++++++#!/ diff --git a/Task/Hello-world-Text/Scala/hello-world-text.scala b/Task/Hello-world-Text/Scala/hello-world-text.scala deleted file mode 100644 index d0337b0351..0000000000 --- a/Task/Hello-world-Text/Scala/hello-world-text.scala +++ /dev/null @@ -1 +0,0 @@ -println("Goodbye, World!") diff --git a/Task/Hofstadter-Q-sequence/Perl/hofstadter-q-sequence.pl b/Task/Hofstadter-Q-sequence/Perl/hofstadter-q-sequence.pl deleted file mode 100644 index 2b16e62a90..0000000000 --- a/Task/Hofstadter-Q-sequence/Perl/hofstadter-q-sequence.pl +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/perl -use warnings; -use strict; - -my @hofstadters = ( 1 , 1 ); -while ( @hofstadters < 100000 ) { - my $nextn = @hofstadters + 1; -# array index counting starts at 0 , so we have to subtract 1 from the numbers! - push @hofstadters , $hofstadters [ $nextn - 1 - $hofstadters[ $nextn - 1 - 1 ] ] - + $hofstadters[ $nextn - 1 - $hofstadters[ $nextn - 2 - 1 ]]; -} -for my $i ( 0..9 ) { - print "$hofstadters[ $i ]\n"; -} -print "The 1000'th term is $hofstadters[ 999 ]!\n"; -my $less_than_preceding = 0; -for my $i ( 0..99998 ) { - $less_than_preceding++ if $hofstadters[ $i + 1 ] < $hofstadters[ $i ]; -} -print "Up to and including the 100000'th term, $less_than_preceding terms are less " . - "than their preceding terms!\n"; diff --git a/Task/Horners-rule-for-polynomial-evaluation/Rust/horners-rule-for-polynomial-evaluation.rust b/Task/Horners-rule-for-polynomial-evaluation/Rust/horners-rule-for-polynomial-evaluation.rust deleted file mode 100644 index 193c2f09e8..0000000000 --- a/Task/Horners-rule-for-polynomial-evaluation/Rust/horners-rule-for-polynomial-evaluation.rust +++ /dev/null @@ -1,15 +0,0 @@ -use core::io; - -fn horner(v: ~[f64], x: f64) -> f64 { - let mut accum = 0.0; - let vlen = v.len(); - for uint::range(0,vlen) |idx| { - accum = accum*x + v[vlen-idx-1]; - }; - accum -} - -fn main() { - let mut v : ~[f64] = ~[-19.,7.,-4.,6.]; - io::println(fmt!("result: %?",horner(v,3.0))); -} diff --git a/Task/I-before-E-except-after-C/Python/i-before-e-except-after-c.py b/Task/I-before-E-except-after-C/Python/i-before-e-except-after-c.py deleted file mode 100644 index 6b4da8bd49..0000000000 --- a/Task/I-before-E-except-after-C/Python/i-before-e-except-after-c.py +++ /dev/null @@ -1,34 +0,0 @@ -import urllib.request -import re - -PLAUSIBILITY_RATIO = 2 - -def plausibility_check(comment, x, y): - print('\n Checking plausibility of: %s' % comment) - if x > PLAUSIBILITY_RATIO * y: - print(' PLAUSIBLE. As we have counts of %i vs %i words, a ratio of %4.1f times' - % (x, y, x / y)) - else: - if x > y: - print(' IMPLAUSIBLE. As although we have counts of %i vs %i words, a ratio of %4.1f times does not make it plausible' - % (x, y, x / y)) - else: - print(' IMPLAUSIBLE, probably contra-indicated. As we have counts of %i vs %i words, a ratio of %4.1f times' - % (x, y, x / y)) - return x > PLAUSIBILITY_RATIO * y - -words = set(urllib.request.urlopen( - 'http://www.puzzlers.org/pub/wordlists/unixdict.txt' - ).read().decode().lower().split()) -cie = sum('cie' in word for word in words) -cei = sum('cei' in word for word in words) -not_c_ie = sum(bool(re.search(r'(^ie|[^c]ie)', word)) for word in words) -not_c_ei = sum(bool(re.search(r'(^ei|[^c]ei)', word)) for word in words) - -print('Checking plausibility of "I before E except after C":') -if ( plausibility_check('I before E when not preceded by C', not_c_ie, not_c_ei) - and plausibility_check('E before I when preceded by C', cei, cie) ): - print('\nOVERALL IT IS PLAUSIBLE!') -else: - print('\nOVERALL IT IS IMPLAUSIBLE!') -print('\n(To be plausible, one word count must exceed another by %i times)' % PLAUSIBILITY_RATIO) diff --git a/Task/I-before-E-except-after-C/REXX/i-before-e-except-after-c.rexx b/Task/I-before-E-except-after-C/REXX/i-before-e-except-after-c.rexx deleted file mode 100644 index ae56a0f3da..0000000000 --- a/Task/I-before-E-except-after-C/REXX/i-before-e-except-after-c.rexx +++ /dev/null @@ -1,35 +0,0 @@ -/*REXX pgm shows plausibility of I before E when not preceded by C, and*/ -/*────────────────────────────── E before I when preceded by C. */ -#.=0 /*zero out various word counters.*/ -parse arg iFID .; if iFID=='' then iFID='UNIXDICT.TXT' /*use default?*/ - - do r=1 while lines(ifid)\==0; _=linein(iFID) /*get a single line.*/ - u=translate(space(_,0)) /*elide superfluous blanks & tabs*/ - if u=='' then iterate /*if a blank line, then ignore it*/ - #.words=#.words+1 /*keep a running count of #words.*/ - if pos('EI',u)\==0 & pos('IE',u)\==0 then #.both=#.both+1 /*has both.*/ - call find 'ie' - call find 'ei' - end /*r*/ - -L=length(#.words) /*use this to align the output #s*/ -say 'words in the ' ifid ' dictionary: ' #.words -say 'words with "IE" and "EI" (in same word): ' right(#.both,L) -say 'words with "IE" and preceded by "C": ' right(#.ie.c ,L) -say 'words with "IE" and not preceded by "C": ' right(#.ie.z ,L) -say 'words with "EI" and preceded by "C": ' right(#.ei.c ,L) -say 'words with "EI" and not preceded by "C": ' right(#.ei.z ,L) -say; mantra='The spelling mantra ' -p1=#.ie.z/max(1,#.ei.z); phrase='"I before E when not preceded by C"' -say mantra phrase ' is ' word("im", 1+(p1>2))'plausible.' -p2=#.ie.c/max(1,#.ei.c); phrase='"E before I when preceded by C"' -say mantra phrase ' is ' word("im", 1+(p2>2))'plausible.' -po=p1>2 & p2>2; say 'Overall, it is' word("im",1+po)'plausible.' -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────FIND subroutine─────────────────────*/ -find: arg x; s=1; do forever; _=pos(x,u,s); if _==0 then leave - if substr(u,_-1+(_==1)*999,1)=='C' then #.x.c=#.x.c+1 - else #.x.z=#.x.z+1 - s=_+1 /*handle case of multiple finds. */ - end /*forever*/ -return diff --git a/Task/Infinity/Scala/infinity.scala b/Task/Infinity/Scala/infinity.scala deleted file mode 100644 index 71b6dcbea1..0000000000 --- a/Task/Infinity/Scala/infinity.scala +++ /dev/null @@ -1,11 +0,0 @@ -scala> 1 / 0. -res2: Double = Infinity - -scala> -1 / 0. -res3: Double = -Infinity - -scala> 1 / Double.PositiveInfinity -res4: Double = 0.0 - -scala> 1 / Double.NegativeInfinity -res5: Double = -0.0 diff --git a/Task/Integer-sequence/Applesoft-BASIC/integer-sequence.applesoft b/Task/Integer-sequence/Applesoft-BASIC/integer-sequence.applesoft deleted file mode 100644 index fd20e13740..0000000000 --- a/Task/Integer-sequence/Applesoft-BASIC/integer-sequence.applesoft +++ /dev/null @@ -1,2 +0,0 @@ - 10 I% = 0 - 20 PRINT I%: IF I% < 32767 THEN I% = I% + 1: GOTO 20 diff --git a/Task/JSON/Ada/json.ada b/Task/JSON/Ada/json.ada deleted file mode 100644 index 6f268bd379..0000000000 --- a/Task/JSON/Ada/json.ada +++ /dev/null @@ -1,41 +0,0 @@ -with Ada.Text_IO; -with GNATCOLL.JSON; - -procedure JSON_Test is - use Ada.Text_IO; - use GNATCOLL.JSON; - - JSON_String : constant String := "{""name"":""Pingu"",""born"":1986}"; - - Penguin : JSON_Value := Create_Object; - Parents : JSON_Array; -begin - Penguin.Set_Field (Field_Name => "name", - Field => "Linux"); - - Penguin.Set_Field (Field_Name => "born", - Field => 1992); - - Append (Parents, Create ("Linus Torvalds")); - Append (Parents, Create ("Alan Cox")); - Append (Parents, Create ("Greg Kroah-Hartman")); - - Penguin.Set_Field (Field_Name => "parents", - Field => Parents); - - Put_Line (Penguin.Write); - - Penguin := Read (JSON_String, "json.errors"); - - Penguin.Set_Field (Field_Name => "born", - Field => 1986); - - Parents := Empty_Array; - Append (Parents, Create ("Otmar Gutmann")); - Append (Parents, Create ("Silvio Mazzola")); - - Penguin.Set_Field (Field_Name => "parents", - Field => Parents); - - Put_Line (Penguin.Write); -end JSON_Test; diff --git a/Task/Jump-anywhere/Java/jump-anywhere.java b/Task/Jump-anywhere/Java/jump-anywhere.java deleted file mode 100644 index faadef6926..0000000000 --- a/Task/Jump-anywhere/Java/jump-anywhere.java +++ /dev/null @@ -1,18 +0,0 @@ -loop1: while (x != 0) { - loop2: for (int i = 0; i < 10; i++) { - loop3: do { - //some calculations... - if (/*some condition*/) { - //this continue will skip the rest of the while loop code and start it over at the next iteration - continue loop1; - } - //more calculations skipped by the continue if it is executed - if (/*another condition*/) { - //this break will end the for loop and jump to its closing brace - break loop2; - } - } while (y < 10); - //loop2 calculations skipped if the break is executed - } - //loop1 calculations executed after loop2 is done or if the break is executed, skipped if the continue is executed -} diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/Common-Lisp/keyboard-input-obtain-a-y-or-n-response.lisp b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Common-Lisp/keyboard-input-obtain-a-y-or-n-response.lisp deleted file mode 100644 index d354398051..0000000000 --- a/Task/Keyboard-input-Obtain-a-Y-or-N-response/Common-Lisp/keyboard-input-obtain-a-y-or-n-response.lisp +++ /dev/null @@ -1,3 +0,0 @@ -(defun rosetta-y-or-n () - (clear-input *query-io*) - (y-or-n-p)) diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/UNIX-Shell/keyboard-input-obtain-a-y-or-n-response.sh b/Task/Keyboard-input-Obtain-a-Y-or-N-response/UNIX-Shell/keyboard-input-obtain-a-y-or-n-response.sh deleted file mode 100644 index 705d6972af..0000000000 --- a/Task/Keyboard-input-Obtain-a-Y-or-N-response/UNIX-Shell/keyboard-input-obtain-a-y-or-n-response.sh +++ /dev/null @@ -1,24 +0,0 @@ -getkey() { - local stty="$(stty -g)" - trap "stty $stty; trap SIGINT; return 128" SIGINT - stty cbreak -echo - local key - while true; do - key=$(dd count=1 2>/dev/null) || return $? - if [ -z "$1" ] || [[ "$key" == [$1] ]]; then - break - fi - done - stty $stty - echo "$key" - return 0 -} - -yorn() { - echo -n "${1:-Press Y or N to continue: }" >&2 - local yorn="$(getkey YyNn)" || return $? - case "$yorn" in - [Yy]) echo >&2 Y; return 0;; - [Nn]) echo >&2 N; return 1;; - esac -} diff --git a/Task/Knapsack-problem-0-1/D/knapsack-problem-0-1.d b/Task/Knapsack-problem-0-1/D/knapsack-problem-0-1.d deleted file mode 100644 index 84f9e89a18..0000000000 --- a/Task/Knapsack-problem-0-1/D/knapsack-problem-0-1.d +++ /dev/null @@ -1,60 +0,0 @@ -import std.stdio, std.algorithm, std.typecons, std.array; - -struct Item { - string name; - int weight, value; -} - -Item[] knapsack01DinamicProg(in Item[] items, in int limit) -pure nothrow { - auto tab = new int[][](items.length + 1, limit + 1); - - foreach (immutable i, immutable it; items) - foreach (immutable w; 1 .. limit + 1) - tab[i + 1][w] = (it.weight > w) ? tab[i][w] : - max(tab[i][w], tab[i][w - it.weight] + it.value); - - Item[] result; - int w = limit; - foreach_reverse (immutable i, immutable it; items) - if (tab[i + 1][w] != tab[i][w]) { - w -= it.weight; - result ~= it; - } - - return result; -} - -void main() { - enum int limit = 400; - immutable Item[] items = [{"map", 9, 150}, - {"compass", 13, 35}, - {"water", 153, 200}, - {"sandwich", 50, 160}, - {"glucose", 15, 60}, - {"tin", 68, 45}, - {"banana", 27, 60}, - {"apple", 39, 40}, - {"cheese", 23, 30}, - {"beer", 52, 10}, - {"suntan cream", 11, 70}, - {"camera", 32, 30}, - {"t-shirt", 24, 15}, - {"trousers", 48, 10}, - {"umbrella", 73, 40}, - {"waterproof trousers", 42, 70}, - {"waterproof overclothes", 43, 75}, - {"note-case", 22, 80}, - {"sunglasses", 7, 20}, - {"towel", 18, 12}, - {"socks", 4, 50}, - {"book", 30, 10}]; - - auto bagged = knapsack01DinamicProg(items, limit); - writeln("Items to pack:"); - bagged.map!q{ a.name }().array().sort().join("\n").writeln(); - const t = reduce!q{ a[] += [b.weight, b.value][] }([0, 0], bagged); - const tot_wv = (t[0] <= limit) ? t : [0, 0]; - writefln("\nFor a total weight of %d and a total value of %d", - tot_wv[0], tot_wv[1]); -} diff --git a/Task/Knapsack-problem-Unbounded/D/knapsack-problem-unbounded.d b/Task/Knapsack-problem-Unbounded/D/knapsack-problem-unbounded.d deleted file mode 100644 index 5b0f340197..0000000000 --- a/Task/Knapsack-problem-Unbounded/D/knapsack-problem-unbounded.d +++ /dev/null @@ -1,53 +0,0 @@ -import std.stdio, std.algorithm, std.typecons; - -struct Bounty { - int value; - double weight, volume; -} - -void main() { - immutable Bounty panacea = {3000, 0.3, 0.025}; - immutable Bounty ichor = {1800, 0.2, 0.015}; - immutable Bounty gold = {2500, 2.0, 0.002}; - immutable Bounty sack = { 0, 25.0, 0.25}; - - Bounty best = {0, 0.0, 0.0}; - Bounty current = {0, 0.0, 0.0}; - Tuple!(int, int, int) bestAmounts; - - immutable maxPanacea = cast(int)(min(sack.weight / panacea.weight, - sack.volume / panacea.volume)); - immutable maxIchor = cast(int)(min(sack.weight / ichor.weight, - sack.volume / ichor.volume)); - immutable maxGold = cast(int)(min(sack.weight / gold.weight, - sack.volume / gold.volume)); - - foreach (nPanacea; 0 .. maxPanacea) - foreach (nIchor; 0 .. maxIchor) - foreach (nGold; 0 .. maxGold) { - current.value = nPanacea * panacea.value + - nIchor * ichor.value + - nGold * gold.value; - current.weight = nPanacea * panacea.weight + - nIchor * ichor.weight + - nGold * gold.weight; - current.volume = nPanacea * panacea.volume + - nIchor * ichor.volume + - nGold * gold.volume; - - if (current.value > best.value && - current.weight <= sack.weight && - current.volume <= sack.volume) { - best = Bounty(current.value, - current.weight, - current.volume); - bestAmounts = tuple(nPanacea, nIchor, nGold); - } - } - - writeln("Maximum value achievable is ", best.value); - writefln("This is achieved by carrying (one solution) %d" ~ - " panacea, %d ichor and %d gold", bestAmounts.tupleof); - writefln("The weight to carry is %4.1f and the volume used is %5.3f", - best.weight, best.volume); -} diff --git a/Task/Knapsack-problem-Unbounded/R/knapsack-problem-unbounded.r b/Task/Knapsack-problem-Unbounded/R/knapsack-problem-unbounded.r deleted file mode 100644 index 2dd624ec94..0000000000 --- a/Task/Knapsack-problem-Unbounded/R/knapsack-problem-unbounded.r +++ /dev/null @@ -1,22 +0,0 @@ -# Define consts -weights <- c(panacea=0.3, ichor=0.2, gold=2.0) -volumes <- c(panacea=0.025, ichor=0.015, gold=0.002) -values <- c(panacea=3000, ichor=1800, gold=2500) -sack.weight <- 25 -sack.volume <- 0.25 -max.items <- floor(pmin(sack.weight/weights, sack.volume/volumes)) - -# Some utility functions -getTotalValue <- function(n) sum(n*values) -getTotalWeight <- function(n) sum(n*weights) -getTotalVolume <- function(n) sum(n*volumes) -willFitInSack <- function(n) getTotalWeight(n) <= sack.weight && getTotalVolume(n) <= sack.volume - -# Find all possible combination, then eliminate those that won't fit in the sack -knapsack <- expand.grid(lapply(max.items, function(n) seq.int(0, n))) -ok <- apply(knapsack, 1, willFitInSack) -knapok <- knapsack[ok,] - -# Find the solutions with the highest value -vals <- apply(knapok, 1, getTotalValue) -knapok[vals == max(vals),] diff --git a/Task/Largest-int-from-concatenated-ints/Java/largest-int-from-concatenated-ints.java b/Task/Largest-int-from-concatenated-ints/Java/largest-int-from-concatenated-ints.java deleted file mode 100644 index e1aa64eb9a..0000000000 --- a/Task/Largest-int-from-concatenated-ints/Java/largest-int-from-concatenated-ints.java +++ /dev/null @@ -1,42 +0,0 @@ -import java.util.*; - -public class IntConcat { - - private static Comparator sorter = new Comparator(){ - @Override - public int compare(Integer o1, Integer o2){ - String o1s = o1.toString(); - String o2s = o2.toString(); - - if(o1s.length() == o2s.length()){ - return o2s.compareTo(o1s); - } - - int mlen = Math.max(o1s.length(), o2s.length()); - while(o1s.length() < mlen * 2) o1s += o1s; - while(o2s.length() < mlen * 2) o2s += o2s; - - return o2s.compareTo(o1s); - } - }; - - public static String join(List things){ - String output = ""; - for(Object obj:things){ - output += obj; - } - return output; - } - - public static void main(String[] args){ - List ints1 = new ArrayList(Arrays.asList(1, 34, 3, 98, 9, 76, 45, 4)); - - Collections.sort(ints1, sorter); - System.out.println(join(ints1)); - - List ints2 = new ArrayList(Arrays.asList(54, 546, 548, 60)); - - Collections.sort(ints2, sorter); - System.out.println(join(ints2)); - } -} diff --git a/Task/Leap-year/Forth/leap-year.fth b/Task/Leap-year/Forth/leap-year.fth deleted file mode 100644 index 26a73830bb..0000000000 --- a/Task/Leap-year/Forth/leap-year.fth +++ /dev/null @@ -1,4 +0,0 @@ -: leap-year? ( y -- ? ) - dup 400 mod 0= if drop true exit then - dup 100 mod 0= if drop false exit then - 4 mod 0= ; diff --git a/Task/Letter-frequency/Ruby/letter-frequency.rb b/Task/Letter-frequency/Ruby/letter-frequency.rb deleted file mode 100644 index ffff7f6abd..0000000000 --- a/Task/Letter-frequency/Ruby/letter-frequency.rb +++ /dev/null @@ -1,10 +0,0 @@ -def letter_frequency(file) - letters = 'a' .. 'z' - File.read(file) . - split(//) . - group_by {|letter| letter.downcase} . - select {|key, val| letters.include? key} . - collect {|key, val| [key, val.length]} -end - -letter_frequency(ARGV[0]).sort_by {|key, val| -val}.each {|pair| p pair} diff --git a/Task/List-comprehensions/Mathematica/list-comprehensions.math b/Task/List-comprehensions/Mathematica/list-comprehensions.math deleted file mode 100644 index 00cab646d2..0000000000 --- a/Task/List-comprehensions/Mathematica/list-comprehensions.math +++ /dev/null @@ -1 +0,0 @@ -Select[Tuples[Range[n], 3], #1[[1]]^2 + #1[[2]]^2 == #1[[3]]^2 &] diff --git a/Task/Literals-String/Haskell/literals-string.hs b/Task/Literals-String/Haskell/literals-string.hs deleted file mode 100644 index 545cd5e5fa..0000000000 --- a/Task/Literals-String/Haskell/literals-string.hs +++ /dev/null @@ -1,5 +0,0 @@ -"abcdef" == "abc\ - \def" - -"abc\ndef" == "abc\n\ - \def" diff --git a/Task/Literals-String/Python/literals-string.py b/Task/Literals-String/Python/literals-string.py deleted file mode 100644 index 910c5791f9..0000000000 --- a/Task/Literals-String/Python/literals-string.py +++ /dev/null @@ -1,2 +0,0 @@ -''' single triple quote ''' -""" double triple quote """ diff --git a/Task/Long-multiplication/C++/long-multiplication.cpp b/Task/Long-multiplication/C++/long-multiplication.cpp deleted file mode 100644 index 190bb5f57c..0000000000 --- a/Task/Long-multiplication/C++/long-multiplication.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include //for mathematical operations on arbitrarily long integers -#include //for input/output of long integers -#include - -int main( ) { - cln::cl_I base = 2 , exponent = 64 ;//cln is a namespace - cln::cl_I factor = cln::expt_pos( base , exponent ) ; - cln::cl_I product = factor * factor ; - std::cout << "The result of 2^64 * 2^64 is " << product << " !\n" ; - return 0 ; -} diff --git a/Task/Long-multiplication/Java/long-multiplication.java b/Task/Long-multiplication/Java/long-multiplication.java deleted file mode 100644 index e322f777cb..0000000000 --- a/Task/Long-multiplication/Java/long-multiplication.java +++ /dev/null @@ -1,13 +0,0 @@ -import java.math.BigInteger; - -public class LongMult { - - public static void main(String[] args) { - BigInteger TwoPow64 = new BigInteger("18446744073709551616"); - System.out.println(mult(TwoPow64, TwoPow64)); - } - - public static BigInteger mult(BigInteger a, BigInteger b){ - return a.multiply(b); - } -} diff --git a/Task/Long-multiplication/PureBasic/long-multiplication.purebasic b/Task/Long-multiplication/PureBasic/long-multiplication.purebasic deleted file mode 100644 index a1f6430b5f..0000000000 --- a/Task/Long-multiplication/PureBasic/long-multiplication.purebasic +++ /dev/null @@ -1,7 +0,0 @@ -XIncludeFile "decimal.pbi" - -Define.Decimal *a, *b -*a=PowerDecimal(IntegerToDecimal(2),IntegerToDecimal(64)) -*b=TimesDecimal(*a,*a,#NoDecimal) - -Print("2^64*2^64 = "+DecimalToString(*b)) diff --git a/Task/Long-multiplication/REXX/long-multiplication.rexx b/Task/Long-multiplication/REXX/long-multiplication.rexx deleted file mode 100644 index 958b37d95b..0000000000 --- a/Task/Long-multiplication/REXX/long-multiplication.rexx +++ /dev/null @@ -1,4 +0,0 @@ -/*REXX program to use and show large multiplication results. */ -numeric digits 1000 /*up to around 8 meg is feasible.*/ -say '2^64 * 2^64 = ' 2**64 * 2**64 -say '2^64 * 2^64 * 2^128 = ' (2**64) * (2**64) * (2**128) diff --git a/Task/Long-multiplication/Seed7/long-multiplication.seed7 b/Task/Long-multiplication/Seed7/long-multiplication.seed7 deleted file mode 100644 index 7e164d2db5..0000000000 --- a/Task/Long-multiplication/Seed7/long-multiplication.seed7 +++ /dev/null @@ -1,7 +0,0 @@ -$ include "seed7_05.s7i"; - include "bigint.s7i"; - -const proc: main is func - begin - writeln(2_**64 * 2_**64); - end func; diff --git a/Task/Look-and-say-sequence/Ruby/look-and-say-sequence.rb b/Task/Look-and-say-sequence/Ruby/look-and-say-sequence.rb deleted file mode 100644 index 07b14b696c..0000000000 --- a/Task/Look-and-say-sequence/Ruby/look-and-say-sequence.rb +++ /dev/null @@ -1,9 +0,0 @@ -def lookandsay(str) - str.gsub(/(.)\1*/) {$&.length.to_s + $1} -end - -num = "1" -10.times do - puts num - num = lookandsay(num) -end diff --git a/Task/Loops-Continue/Scala/loops-continue.scala b/Task/Loops-Continue/Scala/loops-continue.scala deleted file mode 100644 index dc7983d5ac..0000000000 --- a/Task/Loops-Continue/Scala/loops-continue.scala +++ /dev/null @@ -1,4 +0,0 @@ -for(i <- 1 to 10) { - print(i) - if (i%5==0) println() else print(", ") -} diff --git a/Task/Loops-Do-while/Racket/loops-do-while.rkt b/Task/Loops-Do-while/Racket/loops-do-while.rkt deleted file mode 100644 index 1982cfd0bb..0000000000 --- a/Task/Loops-Do-while/Racket/loops-do-while.rkt +++ /dev/null @@ -1,6 +0,0 @@ -#lang racket -(let loop ([n 0]) - (set! n (+ n 1)) - (displayln n) - (unless (zero? (remainder n 6)) - (loop n))) diff --git a/Task/Loops-Infinite/REXX/loops-infinite.rexx b/Task/Loops-Infinite/REXX/loops-infinite.rexx deleted file mode 100644 index 507f31f8cd..0000000000 --- a/Task/Loops-Infinite/REXX/loops-infinite.rexx +++ /dev/null @@ -1,5 +0,0 @@ -/*REXX program to display the word SPAM forever. */ - - do forever - say "SPAM" - end diff --git a/Task/Luhn-test-of-credit-card-numbers/Ruby/luhn-test-of-credit-card-numbers.rb b/Task/Luhn-test-of-credit-card-numbers/Ruby/luhn-test-of-credit-card-numbers.rb deleted file mode 100644 index c8d401fc3f..0000000000 --- a/Task/Luhn-test-of-credit-card-numbers/Ruby/luhn-test-of-credit-card-numbers.rb +++ /dev/null @@ -1,15 +0,0 @@ -def luhn(code) - s1 = s2 = 0 - code.to_s.reverse.chars.each_slice(2) do |odd, even| - s1 += odd.to_i - - double = even.to_i * 2 - double -= 9 if double >= 10 - s2 += double - end - (s1 + s2) % 10 == 0 -end - -[49927398716, 49927398717, 1234567812345678, 1234567812345670].each do |n| - p [n, luhn(n)] -end diff --git a/Task/Mandelbrot-set/C/mandelbrot-set.c b/Task/Mandelbrot-set/C/mandelbrot-set.c deleted file mode 100644 index cd85438988..0000000000 --- a/Task/Mandelbrot-set/C/mandelbrot-set.c +++ /dev/null @@ -1,337 +0,0 @@ - /* - c program: - -------------------------------- - 1. draws Mandelbrot set for Fc(z)=z*z +c - using Mandelbrot algorithm ( boolean escape time ) - ------------------------------- - 2. technique of creating ppm file is based on the code of Claudio Rocchini - http://en.wikipedia.org/wiki/Image:Color_complex_plot.jpg - create 24 bit color graphic file , portable pixmap file = PPM - see http://en.wikipedia.org/wiki/Portable_pixmap - to see the file use external application ( graphic viewer) - */ - #include - int main() - { - /* screen ( integer) coordinate */ - int iX,iY; - const int iXmax = 800; - const int iYmax = 800; - /* world ( double) coordinate = parameter plane*/ - double Cx,Cy; - const double CxMin=-2.5; - const double CxMax=1.5; - const double CyMin=-2.0; - const double CyMax=2.0; - /* */ - double PixelWidth=(CxMax-CxMin)/iXmax; - double PixelHeight=(CyMax-CyMin)/iYmax; - /* color component ( R or G or B) is coded from 0 to 255 */ - /* it is 24 bit color RGB file */ - const int MaxColorComponentValue=255; - FILE * fp; - char *filename="new1.ppm"; - char *comment="# ";/* comment should start with # */ - static unsigned char color[3]; - /* Z=Zx+Zy*i ; Z0 = 0 */ - double Zx, Zy; - double Zx2, Zy2; /* Zx2=Zx*Zx; Zy2=Zy*Zy */ - /* */ - int Iteration; - const int IterationMax=200; - /* bail-out value , radius of circle ; */ - const double EscapeRadius=2; - double ER2=EscapeRadius*EscapeRadius; - /*create new file,give it a name and open it in binary mode */ - fp= fopen(filename,"wb"); /* b - binary mode */ - /*write ASCII header to the file*/ - fprintf(fp,"P6\n %s\n %d\n %d\n %d\n",comment,iXmax,iYmax,MaxColorComponentValue); - /* compute and write image data bytes to the file*/ - for(iY=0;iY - -===PPM Interactive=== -[[file:mandel-C-GL.png|center|400px]] -Infinitely zoomable OpenGL program. Adjustable colors, max iteration, black and white, screen dump, etc. Compile with gcc mandelbrot.c -lglut -lGLU -lGL -lm - -* [[OpenBSD]] users, install freeglut package, and compile with make mandelbrot CPPFLAGS='-I/usr/local/include `pkg-config glu --cflags`' LDLIBS='-L/usr/local/lib -lglut `pkg-config glu --libs` -lm' - -{{libheader|GLUT}} -#include -#include -#include -#include -#include -#include - -void set_texture(); - -typedef struct {unsigned char r, g, b;} rgb_t; -rgb_t **tex = 0; -int gwin; -GLuint texture; -int width, height; -int tex_w, tex_h; -double scale = 1./256; -double cx = -.6, cy = 0; -int color_rotate = 0; -int saturation = 1; -int invert = 0; -int max_iter = 256; - -void render() -{ - double x = (double)width /tex_w, - y = (double)height/tex_h; - - glClear(GL_COLOR_BUFFER_BIT); - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); - - glBindTexture(GL_TEXTURE_2D, texture); - - glBegin(GL_QUADS); - - glTexCoord2f(0, 0); glVertex2i(0, 0); - glTexCoord2f(x, 0); glVertex2i(width, 0); - glTexCoord2f(x, y); glVertex2i(width, height); - glTexCoord2f(0, y); glVertex2i(0, height); - - glEnd(); - - glFlush(); - glFinish(); -} - -int dump = 1; -void screen_dump() -{ - char fn[100]; - int i; - sprintf(fn, "screen%03d.ppm", dump++); - FILE *fp = fopen(fn, "w"); - fprintf(fp, "P6\n%d %d\n255\n", width, height); - for (i = height - 1; i >= 0; i--) - fwrite(tex[i], 1, width * 3, fp); - fclose(fp); - printf("%s written\n", fn); -} - -void keypress(unsigned char key, int x, int y) -{ - switch(key) { - case 'q': glFinish(); - glutDestroyWindow(gwin); - return; - case 27: scale = 1./256; cx = -.6; cy = 0; break; - - case 'r': color_rotate = (color_rotate + 1) % 6; - break; - - case '>': case '.': - max_iter += 128; - if (max_iter > 1 << 15) max_iter = 1 << 15; - printf("max iter: %d\n", max_iter); - break; - - case '<': case ',': - max_iter -= 128; - if (max_iter < 128) max_iter = 128; - printf("max iter: %d\n", max_iter); - break; - - case 'c': saturation = 1 - saturation; - break; - - case 's': screen_dump(); return; - case 'z': max_iter = 4096; break; - case 'x': max_iter = 128; break; - case ' ': invert = !invert; - } - set_texture(); -} - -void hsv_to_rgb(int hue, int min, int max, rgb_t *p) -{ - if (min == max) max = min + 1; - if (invert) hue = max - (hue - min); - if (!saturation) { - p->r = p->g = p->b = 255 * (max - hue) / (max - min); - return; - } - double h = fmod(color_rotate + 1e-4 + 4.0 * (hue - min) / (max - min), 6); -# define VAL 255 - double c = VAL * saturation; - double X = c * (1 - fabs(fmod(h, 2) - 1)); - - p->r = p->g = p->b = 0; - - switch((int)h) { - case 0: p->r = c; p->g = X; return; - case 1: p->r = X; p->g = c; return; - case 2: p->g = c; p->b = X; return; - case 3: p->g = X; p->b = c; return; - case 4: p->r = X; p->b = c; return; - default:p->r = c; p->b = X; - } -} - -void calc_mandel() -{ - int i, j, iter, min, max; - rgb_t *px; - double x, y, zx, zy, zx2, zy2; - min = max_iter; max = 0; - for (i = 0; i < height; i++) { - px = tex[i]; - y = (i - height/2) * scale + cy; - for (j = 0; j < width; j++, px++) { - x = (j - width/2) * scale + cx; - iter = 0; - - zx = hypot(x - .25, y); - if (x < zx - 2 * zx * zx + .25) iter = max_iter; - if ((x + 1)*(x + 1) + y * y < 1/16) iter = max_iter; - - zx = zy = zx2 = zy2 = 0; - for (; iter < max_iter && zx2 + zy2 < 4; iter++) { - zy = 2 * zx * zy + y; - zx = zx2 - zy2 + x; - zx2 = zx * zx; - zy2 = zy * zy; - } - if (iter < min) min = iter; - if (iter > max) max = iter; - *(unsigned short *)px = iter; - } - } - - for (i = 0; i < height; i++) - for (j = 0, px = tex[i]; j < width; j++, px++) - hsv_to_rgb(*(unsigned short*)px, min, max, px); -} - -void alloc_tex() -{ - int i, ow = tex_w, oh = tex_h; - - for (tex_w = 1; tex_w < width; tex_w <<= 1); - for (tex_h = 1; tex_h < height; tex_h <<= 1); - - if (tex_h != oh || tex_w != ow) - tex = realloc(tex, tex_h * tex_w * 3 + tex_h * sizeof(rgb_t*)); - - for (tex[0] = (rgb_t *)(tex + tex_h), i = 1; i < tex_h; i++) - tex[i] = tex[i - 1] + tex_w; -} - -void set_texture() -{ - alloc_tex(); - calc_mandel(); - - glEnable(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, texture); - glTexImage2D(GL_TEXTURE_2D, 0, 3, tex_w, tex_h, - 0, GL_RGB, GL_UNSIGNED_BYTE, tex[0]); - - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - render(); -} - -void mouseclick(int button, int state, int x, int y) -{ - if (state != GLUT_UP) return; - - cx += (x - width / 2) * scale; - cy -= (y - height/ 2) * scale; - - switch(button) { - case GLUT_LEFT_BUTTON: /* zoom in */ - if (scale > fabs(x) * 1e-16 && scale > fabs(y) * 1e-16) - scale /= 2; - break; - case GLUT_RIGHT_BUTTON: /* zoom out */ - scale *= 2; - break; - /* any other button recenters */ - } - set_texture(); -} - - -void resize(int w, int h) -{ - printf("resize %d %d\n", w, h); - width = w; - height = h; - - glViewport(0, 0, w, h); - glOrtho(0, w, 0, h, -1, 1); - - set_texture(); -} - -void init_gfx(int *c, char **v) -{ - glutInit(c, v); - glutInitDisplayMode(GLUT_RGB); - glutInitWindowSize(640, 480); - glutDisplayFunc(render); - - gwin = glutCreateWindow("Mandelbrot"); - - glutKeyboardFunc(keypress); - glutMouseFunc(mouseclick); - glutReshapeFunc(resize); - glGenTextures(1, &texture); - set_texture(); -} - -int main(int c, char **v) -{ - init_gfx(&c, v); - printf("keys:\n\tr: color rotation\n\tc: monochrome\n\ts: screen dump\n\t" - "<, >: decrease/increase max iteration\n\tq: quit\n\tmouse buttons to zoom\n"); - - glutMainLoop(); - return 0; -} diff --git a/Task/Matrix-multiplication/D/matrix-multiplication.d b/Task/Matrix-multiplication/D/matrix-multiplication.d deleted file mode 100644 index fa6534d215..0000000000 --- a/Task/Matrix-multiplication/D/matrix-multiplication.d +++ /dev/null @@ -1,34 +0,0 @@ -import std.stdio, std.string, std.conv, std.numeric, - std.array, std.algorithm; - -bool isRectangular(T)(in T[][] M) /*pure nothrow*/ { - return M.all!(row => row.length == M[0].length); -} - -T[][] matrixMul(T)(in T[][] A, in T[][] B) /*pure nothrow*/ -in { - assert(A.isRectangular && B.isRectangular && - !A.empty && !B.empty && A[0].length == B.length); -} body { - auto result = new T[][](A.length, B[0].length); - auto aux = new T[B.length]; - - foreach (immutable j; 0 .. B[0].length) { - foreach (immutable k, const row; B) - aux[k] = row[j]; - foreach (immutable i, const ai; A) - result[i][j] = dotProduct(ai, aux); - } - - return result; -} - -void main() { - immutable a = [[1, 2], [3, 4], [3, 6]]; - immutable b = [[-3, -8, 3,], [-2, 1, 4]]; - - immutable form = "[%([%(%d, %)],\n %)]]"; - writefln("A = \n" ~ form ~ "\n", a); - writefln("B = \n" ~ form ~ "\n", b); - writefln("A * B = \n" ~ form, matrixMul(a, b)); -} diff --git a/Task/Matrix-transposition/Lua/matrix-transposition.lua b/Task/Matrix-transposition/Lua/matrix-transposition.lua deleted file mode 100644 index dba2c6b21d..0000000000 --- a/Task/Matrix-transposition/Lua/matrix-transposition.lua +++ /dev/null @@ -1,23 +0,0 @@ -function Transpose( m ) - local res = {} - - for i = 1, #m[1] do - res[i] = {} - for j = 1, #m do - res[i][j] = m[j][i] - end - end - - return res -end - --- a test for Transpose(m) -mat = { { 1, 2, 3 }, { 4, 5, 6 } } -erg = Transpose( mat ) -for i = 1, #erg do - for j = 1, #erg[1] do - io.write( erg[i][j] ) - io.write( " " ) - end - io.write( "\n" ) -end diff --git a/Task/Matrix-transposition/MATLAB/matrix-transposition.m b/Task/Matrix-transposition/MATLAB/matrix-transposition.m deleted file mode 100644 index e455b027f3..0000000000 --- a/Task/Matrix-transposition/MATLAB/matrix-transposition.m +++ /dev/null @@ -1,13 +0,0 @@ ->> transpose([1 2;3 4]) - -ans = - - 1 3 - 2 4 - ->> [1 2;3 4].' - -ans = - - 1 3 - 2 4 diff --git a/Task/Maze-generation/REXX/maze-generation.rexx b/Task/Maze-generation/REXX/maze-generation.rexx deleted file mode 100644 index f268d83806..0000000000 --- a/Task/Maze-generation/REXX/maze-generation.rexx +++ /dev/null @@ -1,60 +0,0 @@ -/*REXX program to generate and display a (rectangular) maze. */ -height=0; @.=0 /*default for all cells visited.*/ -parse arg rows cols seed . /*allow user to specify maze size*/ -if rows='' | rows==',' then rows=19 /*No rows given? Use the default*/ -if cols='' | cols==',' then cols=19 /*No cols given? Use the default*/ -if seed\=='' then call random ,,seed /*use a seed for repeatability. */ -call buildRow '┌'copies('─┬',cols-1)'─┐' - /*(below) build maze's grid & pop*/ - do r=1 for rows; _=; __=; hp= '|'; hj='├' - do c=1 for cols; _= _||hp'1'; __=__||hj'─'; hj='┼'; hp='│' - end /*c*/ - call buildRow _'│' - if r\==rows then call buildRow __'┤' - end /*r*/ - -call buildRow '└'copies('─┴',cols-1)'─┘' -r!=random(1,rows)*2; c!=random(1,cols)*2; @.r!.c!=0 /*choose 1st cell*/ - - do forever; n=hood(r!,c!); if n==0 then if \fcell() then leave - call ?; @._r._c=0 - ro=r!; co=c!; r!=_r; c!=_c - ?.zr=?.zr%2; ?.zc=?.zc%2 - rw=ro+?.zr; cw=co+?.zc - @.rw.cw='·' - end /*forever*/ - - do r=1 for height; _= /*display the maze. */ - do c=1 for cols*2 + 1; _=_ || @.r.c; end - if r//2 then _=translate(_,'-','fa'x) /*translate to minus*/ - _=translate(_,'\','fa'x) /*trans to backslash*/ - _=changestr(1,_,111) /*these four ────────────────────*/ - _=changestr(0,_,000) /*─── statements are ────────────*/ - _=changestr('-',_," ") /*──────── used for preserving ──*/ - _=changestr('─',_,"───") /*──────────── the aspect ratio. */ - say translate(_,'│',"|\10") /*make it presentable for screen.*/ - end /*r*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────FCELL subroutine────────────────────*/ -fcell: do r=1 for rows; r2=r+r - do c=1 for cols; c2=c+c - if hood(r2,c2)==1 then do; r!=r2; c!=c2; @.r!.c!=0; return 1 - end - end /*c*/ - end /*r*/ -return 0 -/*──────────────────────────────────@ subroutine────────────────────────*/ -@: parse arg _r,_c; return @._r._c -/*──────────────────────────────────? subroutine────────────────────────*/ -?: do forever; ?.=0; ?=random(1,4) - if ?==1 then ?.zc=-2 /*north*/ - if ?==2 then ?.zr=+2 /* east*/ - if ?==3 then ?.zc=+2 /*south*/ - if ?==4 then ?.zr=-2 /* west*/ - _r=r!+?.zr; _c=c!+?.zc; if @._r._c==1 then return - end /*forever*/ -/*──────────────────────────────────HOOD subroutine─────────────────────*/ -hood: parse arg rh,ch; return @(rh+2,ch)+@(rh-2,ch)+@(rh,ch-2)+@(rh,ch+2) -/*──────────────────────────────────BUILDROW subroutine─────────────────*/ -buildRow: parse arg z; height=height+1; width=length(z) - do c=1 for width; @.height.c=substr(z,c,1); end; return diff --git a/Task/Menu/OCaml/menu.ocaml b/Task/Menu/OCaml/menu.ocaml deleted file mode 100644 index fba77f0d9c..0000000000 --- a/Task/Menu/OCaml/menu.ocaml +++ /dev/null @@ -1,9 +0,0 @@ -let rec select choices prompt = (* "choices" is an array of strings *) - if Array.length choices = 0 then invalid_arg "no choices"; - Array.iteri (Printf.printf "%d: %s\n") choices; - print_string prompt; - let index = read_int () in - if index >= 0 && index < Array.length choices then - choices.(index) - else - select choices prompt diff --git a/Task/Metered-concurrency/Haskell/metered-concurrency.hs b/Task/Metered-concurrency/Haskell/metered-concurrency.hs deleted file mode 100644 index cbed993e56..0000000000 --- a/Task/Metered-concurrency/Haskell/metered-concurrency.hs +++ /dev/null @@ -1,19 +0,0 @@ -import Control.Concurrent -import Control.Monad - -worker :: QSem -> MVar String -> Int -> IO () -worker q m n = do - waitQSem q - putMVar m $ "Worker " ++ show n ++ " has acquired the lock." - threadDelay 2000000 -- microseconds! - signalQSem q - putMVar m $ "Worker " ++ show n ++ " has released the lock." - -main :: IO () -main = do - q <- newQSem 3 - m <- newEmptyMVar - let workers = 5 - prints = 2 * workers - mapM_ (forkIO . worker q m) [1..workers] - replicateM_ prints $ takeMVar m >>= print diff --git a/Task/Middle-three-digits/C/middle-three-digits.c b/Task/Middle-three-digits/C/middle-three-digits.c deleted file mode 100644 index c8577e3c6f..0000000000 --- a/Task/Middle-three-digits/C/middle-three-digits.c +++ /dev/null @@ -1,32 +0,0 @@ -#include -#include -#include - -// we return a static buffer; caller wants it, caller copies it -char * mid3(int n) -{ - static char buf[32]; - int l; - sprintf(buf, "%d", n > 0 ? n : -n); - l = strlen(buf); - if (l < 3 || !(l & 1)) return 0; - l = l / 2 - 1; - buf[l + 3] = 0; - return buf + l; -} - -int main(void) -{ - int x[] = {123, 12345, 1234567, 987654321, 10001, -10001, - -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0, - 1234567890}; - - int i; - char *m; - for (i = 0; i < sizeof(x)/sizeof(x[0]); i++) { - if (!(m = mid3(x[i]))) - m = "error"; - printf("%d: %s\n", x[i], m); - } - return 0; -} diff --git a/Task/Middle-three-digits/COBOL/middle-three-digits.cobol b/Task/Middle-three-digits/COBOL/middle-three-digits.cobol deleted file mode 100644 index 802fe9b080..0000000000 --- a/Task/Middle-three-digits/COBOL/middle-three-digits.cobol +++ /dev/null @@ -1,91 +0,0 @@ -identification division. -program-id. middle3. -environment division. -data division. -working-storage section. -01 num pic 9(9). - 88 num-too-small values are -99 thru 99. -01 num-disp pic ---------9. - -01 div pic 9(9). -01 mod pic 9(9). -01 mod-disp pic 9(3). - -01 digit-counter pic 999. -01 digit-div pic 9(9). - 88 no-more-digits value 0. -01 digit-mod pic 9(9). - 88 is-even value 0. - -01 multiplier pic 9(9). - -01 value-items. - 05 filler pic s9(9) value 123. - 05 filler pic s9(9) value 12345. - 05 filler pic s9(9) value 1234567. - 05 filler pic s9(9) value 987654321. - 05 filler pic s9(9) value 10001. - 05 filler pic s9(9) value -10001. - 05 filler pic s9(9) value -123. - 05 filler pic s9(9) value -100. - 05 filler pic s9(9) value 100. - 05 filler pic s9(9) value -12345. - 05 filler pic s9(9) value 1. - 05 filler pic s9(9) value 2. - 05 filler pic s9(9) value -1. - 05 filler pic s9(9) value -10. - 05 filler pic s9(9) value 2002. - 05 filler pic s9(9) value -2002. - 05 filler pic s9(9) value 0. - -01 value-array redefines value-items. - 05 items pic s9(9) occurs 17 times indexed by item. - -01 result pic x(20). - -procedure division. -10-main. - perform with test after varying item from 1 by 1 until items(item) = 0 - move items(item) to num - move items(item) to num-disp - perform 20-check - display num-disp " --> " result - end-perform. - stop run. - -20-check. - if num-too-small - move "Number too small" to result - exit paragraph - end-if. - - perform 30-count-digits. - divide digit-counter by 2 giving digit-div remainder digit-mod. - if is-even - move "Even number of digits" to result - exit paragraph - end-if. - - *> if digit-counter is 5, mul by 10 - *> if digit-counter is 7, mul by 100 - *> if digit-counter is 9, mul by 1000 - - if digit-counter > 3 - compute multiplier rounded = 10 ** (((digit-counter - 5) / 2) + 1) - divide num by multiplier giving num - divide num by 1000 giving div remainder mod - move mod to mod-disp - else - move num to mod-disp - end-if. - move mod-disp to result. - exit paragraph. - -30-count-digits. - move zeroes to digit-counter. - move num to digit-div. - perform with test before until no-more-digits - divide digit-div by 10 giving digit-div remainder digit-mod - add 1 to digit-counter - end-perform. - exit paragraph. diff --git a/Task/Middle-three-digits/REXX/middle-three-digits.rexx b/Task/Middle-three-digits/REXX/middle-three-digits.rexx deleted file mode 100644 index 20ef226b47..0000000000 --- a/Task/Middle-three-digits/REXX/middle-three-digits.rexx +++ /dev/null @@ -1,28 +0,0 @@ -/* REXX *************************************************************** -* 03.02.2013 Walter Pachl -**********************************************************************/ -sl='123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345', - '2 -1 -10 2002 -2002 0 abc 1e3 -17e-3' -Do While sl<>'' /* loop through test values */ - Parse Var sl s sl /* pick next value */ - Call mid3 s /* test it */ - End -Exit -mid3: Procedure -Parse arg d /* take the argument */ -Select /* first test for valid input */ - When datatype(d)<>'NUM' Then Call error 'not a number' - When pos('E',translate(d))>0 Then Call error 'not just digits' - When length(abs(d))<3 Then Call error 'less than 3 digits' - When length(abs(d))//2<>1 Then Call error 'not an odd number of digits' - Otherwise Do /* input is ok */ - dx=abs(d) /* get rid of optional sign */ - ld=length(dx) /* length of digit string */ - z=(ld-3)/2 /* number of digits to cut */ - Say left(d,12) '->' substr(dx,z+1,3) /* show middle 3 digits */ - End - End - Return -error: - Say left(d,12) '->' arg(1) /* tell about the problem */ - Return diff --git a/Task/Miller-Rabin-primality-test/Python/miller-rabin-primality-test.py b/Task/Miller-Rabin-primality-test/Python/miller-rabin-primality-test.py deleted file mode 100644 index 092d294d11..0000000000 --- a/Task/Miller-Rabin-primality-test/Python/miller-rabin-primality-test.py +++ /dev/null @@ -1,78 +0,0 @@ -import random - -_mrpt_num_trials = 5 # number of bases to test - -def is_probable_prime(n): - """ - Miller-Rabin primality test. - - A return value of False means n is certainly not prime. A return value of - True means n is very likely a prime. - - >>> is_probable_prime(1) - Traceback (most recent call last): - ... - AssertionError - >>> is_probable_prime(2) - True - >>> is_probable_prime(3) - True - >>> is_probable_prime(4) - False - >>> is_probable_prime(5) - True - >>> is_probable_prime(123456789) - False - - >>> primes_under_1000 = [i for i in range(2, 1000) if is_probable_prime(i)] - >>> len(primes_under_1000) - 168 - >>> primes_under_1000[-10:] - [937, 941, 947, 953, 967, 971, 977, 983, 991, 997] - - >>> is_probable_prime(6438080068035544392301298549614926991513861075340134\ -3291807343952413826484237063006136971539473913409092293733259038472039\ -7133335969549256322620979036686633213903952966175107096769180017646161\ -851573147596390153) - True - - >>> is_probable_prime(7438080068035544392301298549614926991513861075340134\ -3291807343952413826484237063006136971539473913409092293733259038472039\ -7133335969549256322620979036686633213903952966175107096769180017646161\ -851573147596390153) - False - """ - assert n >= 2 - # special case 2 - if n == 2: - return True - # ensure n is odd - if n % 2 == 0: - return False - # write n-1 as 2**s * d - # repeatedly try to divide n-1 by 2 - s = 0 - d = n-1 - while True: - quotient, remainder = divmod(d, 2) - if remainder == 1: - break - s += 1 - d = quotient - assert(2**s * d == n-1) - - # test the base a to see whether it is a witness for the compositeness of n - def try_composite(a): - if pow(a, d, n) == 1: - return False - for i in range(s): - if pow(a, 2**i * d, n) == n-1: - return False - return True # n is definitely composite - - for i in range(_mrpt_num_trials): - a = random.randrange(2, n) - if try_composite(a): - return False - - return True # no base tested showed n as composite diff --git a/Task/Modular-inverse/Icon/modular-inverse.icon b/Task/Modular-inverse/Icon/modular-inverse.icon deleted file mode 100644 index defdfc4f04..0000000000 --- a/Task/Modular-inverse/Icon/modular-inverse.icon +++ /dev/null @@ -1,16 +0,0 @@ -procedure main(args) - a := integer(args[1]) | 42 - b := integer(args[2]) | 2017 - write(mul_inv(a,b)) -end - -procedure mul_inv(a,b) - if b == 1 then return 1 - (b0 := b, x0 := 0, x1 := 1) - while a > 1 do { - q := a/b - (t := b, b := a%b, a := t) - (t := x0, x0 := x1-q*x0, x1 := t) - } - return if (x1 > 0) then x1 else x1+b0 -end diff --git a/Task/N-queens-problem/Common-Lisp/n-queens-problem.lisp b/Task/N-queens-problem/Common-Lisp/n-queens-problem.lisp deleted file mode 100644 index b84ee246e3..0000000000 --- a/Task/N-queens-problem/Common-Lisp/n-queens-problem.lisp +++ /dev/null @@ -1,22 +0,0 @@ -(defun n-queens (n m) - (if (= n 1) - (loop for x from 1 to m collect (list x)) - (loop for sol in (n-queens (1- n) m) nconc - (loop for col from 1 to m when - (loop for row from 0 to (length sol) for c in sol - always (and (/= col c) - (/= (abs (- c col)) (1+ row))) - finally (return (cons col sol))) - collect it)))) - -(defun show-solution (b n) - (loop for i in b do - (format t "~{~A~^~}~%" - (loop for x from 1 to n collect (if (= x i) "Q " ". ")))) - (terpri)) - -(let ((i 0) (n 8)) - (mapc #'(lambda (s) - (format t "Solution ~a:~%" (incf i)) - (show-solution s n)) - (n-queens n n))) diff --git a/Task/N-queens-problem/Haskell/n-queens-problem.hs b/Task/N-queens-problem/Haskell/n-queens-problem.hs deleted file mode 100644 index 5048f7fdfb..0000000000 --- a/Task/N-queens-problem/Haskell/n-queens-problem.hs +++ /dev/null @@ -1,31 +0,0 @@ -import Control.Monad -import Data.List - --- given n, "queens n" solves the n-queens problem, returning a list of all the --- safe arrangements. each solution is a list of the columns where the queens are --- located for each row -queens :: Int -> [[Int]] -queens n = map fst $ foldM oneMoreQueen ([],[1..n]) [1..n] where - - -- foldM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a - -- foldM folds (from left to right) in the list monad, which is convenient for - -- "nondeterminstically" finding "all possible solutions" of something. the - -- initial value [] corresponds to the only safe arrangement of queens in 0 rows - - -- given a safe arrangement y of queens in the first i rows, and a list of - -- possible choices, "oneMoreQueen y _" returns a list of all the safe - -- arrangements of queens in the first (i+1) rows along with remaining choices - oneMoreQueen (y,d) _ = [ (x:y, d\\[x]) | x <- d, safe x y 1] - --- "safe x y n" tests whether a queen at column x is safe from previous --- queens as recorded in y, at the distance n rows away -safe x [] n = True -safe x (c:y) n = and [ x /= c , x /= c + n , x /= c - n , safe x y (n+1)] - --- prints what the board looks like for a solution; with an extra newline -printSolution y = let n = length y in - do mapM_ (\x -> putStrLn [if z == x then 'Q' else '.' | z <- [1..n]]) y - putStrLn "" - --- prints all the solutions for 6 queens -main = mapM_ printSolution $ queens 6 diff --git a/Task/Non-continuous-subsequences/Ruby/non-continuous-subsequences.rb b/Task/Non-continuous-subsequences/Ruby/non-continuous-subsequences.rb deleted file mode 100644 index ce9adbd560..0000000000 --- a/Task/Non-continuous-subsequences/Ruby/non-continuous-subsequences.rb +++ /dev/null @@ -1,21 +0,0 @@ -class Array - def func_power_set - inject([[]]) { |ps,item| # for each item in the Array - ps + # take the powerset up to now and add - ps.map { |e| e + [item] } # it again, with the item appended to each element - } - end - - def non_continuous_subsequences - func_power_set.find_all {|seq| not seq.continuous} - end - - def continuous - each_cons(2) {|a, b| return false if a+1 != b} - true - end -end - -p (1..3).to_a.non_continuous_subsequences -p (1..4).to_a.non_continuous_subsequences -p (1..5).to_a.non_continuous_subsequences diff --git a/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata.d b/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata.d deleted file mode 100644 index f479ef84ce..0000000000 --- a/Task/One-dimensional-cellular-automata/D/one-dimensional-cellular-automata.d +++ /dev/null @@ -1,19 +0,0 @@ -import std.stdio, std.algorithm; - -void main() { - enum ngenerations = 10; - enum initial = "0011101101010101001000"; - enum table = "00010110"; - - char[initial.length + 2] A = '0', B = '0'; - A[1 .. $-1] = initial; - foreach (_; 0 .. ngenerations) { - foreach (i; 1 .. A.length-1) { - write(A[i] == '0' ? '_' : '#'); - int val = (A[i-1]-'0' << 2) | (A[i]-'0' << 1) | (A[i+1]-'0'); - B[i] = table[val]; - } - swap(A, B); - writeln(); - } -} diff --git a/Task/One-dimensional-cellular-automata/Nimrod/one-dimensional-cellular-automata.nimrod b/Task/One-dimensional-cellular-automata/Nimrod/one-dimensional-cellular-automata.nimrod deleted file mode 100644 index 5a1f8e2481..0000000000 --- a/Task/One-dimensional-cellular-automata/Nimrod/one-dimensional-cellular-automata.nimrod +++ /dev/null @@ -1,61 +0,0 @@ -import math -randomize() - -type - TBoolArray = array[0..30, bool] # an array that is indexed with 0..10 - TSymbols = tuple[on: char , off: char] - -const - num_turns = 20 - symbols:TSymbols = ('#',' ') - -proc `==` (x:TBoolArray,y:TBoolArray): bool = - if len(x) != len(y): - return False - for i in 0..(len(x)-1): - if x[i] != y[i]: - return False - return True - -proc count_neighbours(map:TBoolArray , tile:int):int = - result = 0 - if tile != len(map)-1 and map[tile+1]: - result += 1 - if tile != 0 and map[tile-1]: - result += 1 - -proc print_map(map:TBoolArray, symbols:TSymbols) = - for i in map: - if i: - write(stdout,symbols[0]) - else: - write(stdout,symbols[1]) - write(stdout,"\n") - -proc random_map(): TBoolArray = - var map = [False,False,False,False,False,False,False,False,False,False,False, - False,False,False,False,False,False,False,False,False,False,False, - False,False,False,False,False,False,False,False,False] - for i in 0..(len(map)-1): - map[i] = bool(random(2)) - return map - -#make the map -var map:TBoolArray -map = random_map() -print_map(map,symbols) -for i in 0..num_turns: - var new_map = map - for j in 0..(len(map)-1): - if map[j]: - if count_neighbours(map, j) == 2 or - count_neighbours(map, j) == 0: - new_map[j] = False - else: - if count_neighbours(map, j) == 2: - new_map[j] = True - if new_map == map: - print_map(map,symbols) - break - map = new_map - print_map(map,symbols) diff --git a/Task/Palindrome-detection/PARI-GP/palindrome-detection.pari b/Task/Palindrome-detection/PARI-GP/palindrome-detection.pari deleted file mode 100644 index a59b93abd5..0000000000 --- a/Task/Palindrome-detection/PARI-GP/palindrome-detection.pari +++ /dev/null @@ -1,7 +0,0 @@ -ispal(s)={ - s=Vec(s); - for(i=1,#v\2, - if(v[i]!=v[#v-i+1],return(0)) - ); - 1 -}; diff --git a/Task/Palindrome-detection/REXX/palindrome-detection.rexx b/Task/Palindrome-detection/REXX/palindrome-detection.rexx deleted file mode 100644 index 01c85ad9f1..0000000000 --- a/Task/Palindrome-detection/REXX/palindrome-detection.rexx +++ /dev/null @@ -1,13 +0,0 @@ -/*REXX pgm checks if a phrase is palindromic (ignoring blanks and case).*/ -y = 'In girum imus nocte et consumimur igni' /* [↓] translation.*/ - /*We walk around in the night and we are burnt by the fire (of love).*/ -say 'string = ' y -say -if isPal(y) then say 'The string is palindromic.' - else say "The string isn't palindromic." -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────ISPAL subroutine────────────────────*/ -isPal: procedure; arg x /*uppercases the value of arg X. */ -x=space(x,0) /*remove all blanks from the str.*/ -return x==reverse(x) /*returns 1 if exactly equal, */ - /* " 0 if not equal. */ diff --git a/Task/Parsing-RPN-to-infix-conversion/D/parsing-rpn-to-infix-conversion.d b/Task/Parsing-RPN-to-infix-conversion/D/parsing-rpn-to-infix-conversion.d deleted file mode 100644 index aa08cce6b3..0000000000 --- a/Task/Parsing-RPN-to-infix-conversion/D/parsing-rpn-to-infix-conversion.d +++ /dev/null @@ -1,43 +0,0 @@ -import std.stdio, std.string, std.array; - -void parseRPN(in string e) { - enum nPrec = 9; - static struct Info { int prec; bool rAssoc; } - immutable /*static*/ opa = ["^": Info(4, true), - "*": Info(3, false), - "/": Info(3, false), - "+": Info(2, false), - "-": Info(2, false)]; - - writeln("\nPostfix input: ", e); - static struct Sf { int prec; string expr; } - Sf[] stack; - foreach (immutable tok; e.split()) { - writeln("Token: ", tok); - if (tok in opa) { - immutable op = opa[tok]; - immutable rhs = stack.back; - stack.popBack(); - auto lhs = &stack.back; - if (lhs.prec < op.prec || - (lhs.prec == op.prec && op.rAssoc)) - lhs.expr = "(" ~ lhs.expr ~ ")"; - lhs.expr ~= " " ~ tok ~ " "; - lhs.expr ~= (rhs.prec < op.prec || - (rhs.prec == op.prec && !op.rAssoc)) ? - "(" ~ rhs.expr ~ ")" : - rhs.expr; - lhs.prec = op.prec; - } else - stack ~= Sf(nPrec, tok); - foreach (immutable f; stack) - writefln(` %d "%s"`, f.prec, f.expr); - } - writeln("Infix result: ", stack[0].expr); -} - -void main() { - foreach (immutable test; ["3 4 2 * 1 5 - 2 3 ^ ^ / +", - "1 2 + 3 4 + ^ 5 6 + ^"]) - parseRPN(test); -} diff --git a/Task/Parsing-Shunting-yard-algorithm/Haskell/parsing-shunting-yard-algorithm.hs b/Task/Parsing-Shunting-yard-algorithm/Haskell/parsing-shunting-yard-algorithm.hs deleted file mode 100644 index 8c5fe0bea6..0000000000 --- a/Task/Parsing-Shunting-yard-algorithm/Haskell/parsing-shunting-yard-algorithm.hs +++ /dev/null @@ -1,53 +0,0 @@ -import qualified Data.Map as M -import Text.Printf -import Data.List -import System.Environment - -data Assoc = L | R deriving (Eq, Show) -data Op = Op Assoc Int - -ops = M.fromList [("^", Op R 4) - ,("*", Op L 3),("/", Op L 3) - ,("+", Op L 2),("-", Op L 2)] - -assoc t = case M.lookup t ops of - Just (Op a p) -> a - Nothing -> error "Bad lookup (assoc)" - -prec t = case M.lookup t ops of - Just (Op a p) -> p - Nothing -> error "Bad lookup (prec)" - -isDouble t = case reads t :: [(Double, String)] of - [(_, "")] -> True - _ -> False - -finish (vs, fs, xs, _) = ((reverse fs ++ vs), [], xs, "Finished") - -eval xs = (intermediates ++ [(finish $ last intermediates)]) - where intermediates = scanl f ([], [], words xs, "").words $ xs - f (vs, fs, ts, msg) t | isDouble t = ((t:vs), fs, tail ts, "Writing '" - ++ t) - | t `M.member` ops = pushOp t (vs, fs, ts, msg) - | t == "(" = (vs, (t:fs), tail ts, "Pushing '('") - | t == ")" = (((takeWhile (/="(") fs) ++ vs), - (tail $ dropWhile (/="(") fs), - tail ts, "Writing ops till ')'") - -pushOp op1 (vs, fs, ts, msg) = if op2isOp && - ((assoc op1 == L && prec op1 <= prec op2) || - (prec op1 < prec op2)) - then ((op2:vs), (op1:tail fs), tail ts, - "Writing '" ++ op2 ++ - "', pushing " ++ op1) - else (vs, (op1:fs), tail ts, "Pushing '" ++ op1 ++ "'") - where (op2isOp, op2) = ((not $ null fs) && (op2 `M.member` ops), head fs) - -showData (vs, fs, xs, msg) = concat [printf "%30s" (intercalate " " (reverse vs)) , " " - ,printf "%10s" (intercalate " " fs) , " " - ,printf "%35s" (intercalate " " xs) , " " - ,printf "%s" msg] - -showAll xs = intercalate "\n" $ map showData xs - -main = do putStrLn.showAll.eval $ "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" diff --git a/Task/Permutation-test/D/permutation-test.d b/Task/Permutation-test/D/permutation-test.d deleted file mode 100644 index a692a88297..0000000000 --- a/Task/Permutation-test/D/permutation-test.d +++ /dev/null @@ -1,32 +0,0 @@ -import std.stdio, std.algorithm, std.array; -// http://rosettacode.org/wiki/Combinations#D -import combinations3: combinations; - -auto permTest(T)(T[] a, T[] b, in int precisionAdjust=100) { - alias reduce!q{a + b} sum; // statistic can be degenerate to sum - - auto ab = a ~ b; - ab[] *= precisionAdjust; // scale up magnitude - auto tObs = sum(ab[0 .. a.length]); - auto comb = combinations!false(ab, a.length); - - // combinations() isn't a Range yet - //immutable int under = comb.count!(c => stat(c) <= tObs)(); - int under = 0; - foreach (c; comb) - if (sum(c) <= tObs) - under++; - - return 1.0L * under / comb.length; -} - -void main() { - auto treatment = [0.85, 0.88, 0.75, 0.66, 0.25, 0.29, - 0.83, 0.39, 0.97]; - auto control = [0.68, 0.41, 0.10, 0.49, 0.16, 0.65, - 0.32, 0.92, 0.28, 0.98]; - - auto r = permTest(treatment, control); - writefln("under =%6.2f%%\nover =%6.2f%%", - r * 100.0, (1 - r) * 100.0); -} diff --git a/Task/Permutations/Ada/permutations.ada b/Task/Permutations/Ada/permutations.ada deleted file mode 100644 index dd6c491a1c..0000000000 --- a/Task/Permutations/Ada/permutations.ada +++ /dev/null @@ -1,113 +0,0 @@ --- perm.adb --- print all permutations of 1 .. n --- where n is given as a command line argument --- to compile with GNAT : gnat make perm.adb --- to call on command line : perm n -with Ada.Text_IO, Ada.Command_Line; - -procedure Perm is - use Ada.Text_IO, Ada.Command_Line; - N : Integer; -begin - if Argument_Count /= 1 - then - Put_Line (Command_Name & " n (with n >= 1)"); - return; - else - N := Integer'Value (Argument (1)); - end if; - declare - subtype Element is Integer range 1 .. N; - type Permutation is array (Element'Range) of Element; - P : Permutation; - Is_Last : Boolean := False; - - procedure Swap (A, B : in out Integer) is - C : Integer := A; - begin - A := B; - B := C; - end; - - -- compute next permutation in lexicographic order - -- iterative algorithm : - -- find longest tail-decreasing sequence in p - -- the elements from this tail cannot be permuted to get a new permutation, so - -- reverse this tail, to start from an increaing sequence, and - -- exchange the element x preceding the tail, with the minimum value in the tail, - -- that is also greater than x - procedure Next is - I, J, K : Element; - begin - -- find longest tail decreasing sequence - -- after the loop, this sequence is i+1 .. n, - -- and the ith element will be exchanged later - -- with some element of the tail - Is_Last := True; - I := N - 1; - loop - if P (I) < P (I+1) - then - Is_Last := False; - exit; - end if; - - -- next instruction will raise an exception if i = 1, so - -- exit now (this is the last permutation) - exit when I = 1; - I := I - 1; - end loop; - - -- if all the elements of the permutation are in - -- decreasing order, this is the last one - if Is_Last then - return; - end if; - - -- sort the tail, i.e. reverse it, since it is in decreasing order - J := I + 1; - K := N; - while J < K loop - Swap (P (J), P (K)); - J := J + 1; - K := K - 1; - end loop; - - -- find lowest element in the tail greater than the ith element - J := N; - while P (J) > P (I) loop - J := J - 1; - end loop; - J := J + 1; - - -- exchange them - -- this will give the next permutation in lexicographic order, - -- since every element from ith to the last is minimum - Swap (P (I), P (J)); - end next; - - procedure Print is - begin - for I in Element'Range loop - Put (Integer'Image (P (I))); - end loop; - New_Line; - end Print; - - -- initialize the permutation - procedure Init is - begin - for I in Element'Range loop - P (I) := I; - end loop; - end Init; - - begin - Init; - while not Is_Last loop - Print; - Next; - end loop; - end; - -end Perm; diff --git a/Task/Pi/Perl/pi.pl b/Task/Pi/Perl/pi.pl deleted file mode 100644 index e70eb209e5..0000000000 --- a/Task/Pi/Perl/pi.pl +++ /dev/null @@ -1,55 +0,0 @@ -use Math::BigInt; -use bigint; - -# Pi/4 = 4 arctan 1/5 - arctan 1/239 -# expanding it with Taylor series with what's probably the dumbest method - -my ($ds, $ns) = (1, 0); -my ($n5, $d5) = (16 * (25 * 3 - 1), 3 * 5**3); -my ($n2, $d2) = (4 * (239 * 239 * 3 - 1), 3 * 239**3); - -sub next_term { - my ($coef, $p) = @_[1, 2]; - $_[0] /= ($p - 4) * ($p - 2); - $_[0] *= $p * ($p + 2) * $coef**4; -} - -my $p2 = 5; -my $pow = 1; - -$| = 1; -for (my $x = 5; ; $x += 4) { - ($ns, $ds) = ($ns * $d5 + $n5 * $pow * $ds, $ds * $d5); - - next_term($d5, 5, $x); - $n5 = 16 * (5 * 5 * ($x + 2) - $x); - - while ($d5 > $d2) { - ($ns, $ds) = ($ns * $d2 - $n2 * $pow * $ds, $ds * $d2); - $n2 = 4 * (239 * 239 * ($p2 + 2) - $p2); - next_term($d2, 239, $p2); - $p2 += 4; - } - - my $ppow = 1; - while ($pow * $n5 * 5**4 < $d5 && $pow * $n2 * $n2 * 239**4 < $d2) { - $pow *= 10; - $ppow *= 10; - } - - if ($ppow > 1) { - $ns *= $ppow; - #FIX? my $out = $ns->bdiv($ds); # bugged? - my $out = $ns / $ds; - $ns %= $ds; - - $out = ("0" x (length($ppow) - length($out) - 1)) . $out; - print $out; - } - - if ( $p2 % 20 == 1) { - my $g = Math::BigInt::bgcd($ds, $ns); - $ds /= $g; - $ns /= $g; - } -} diff --git a/Task/Pig-the-dice-game/Java/pig-the-dice-game.java b/Task/Pig-the-dice-game/Java/pig-the-dice-game.java deleted file mode 100644 index 6160fa4caa..0000000000 --- a/Task/Pig-the-dice-game/Java/pig-the-dice-game.java +++ /dev/null @@ -1,42 +0,0 @@ -import java.util.*; - -public class PigDice { - - public static void main(String[] args) { - final int maxScore = 100; - final int playerCount = 2; - final String[] yesses = {"y", "Y", ""}; - - int[] safeScore = new int[2]; - int player = 0, score = 0; - - Scanner sc = new Scanner(System.in); - Random rnd = new Random(); - - while (true) { - System.out.printf(" Player %d: (%d, %d) Rolling? (y/n) ", player, - safeScore[player], score); - if (safeScore[player] + score < maxScore - && Arrays.asList(yesses).contains(sc.nextLine())) { - final int rolled = rnd.nextInt(6) + 1; - System.out.printf(" Rolled %d\n", rolled); - if (rolled == 1) { - System.out.printf(" Bust! You lose %d but keep %d\n\n", - score, safeScore[player]); - } else { - score += rolled; - continue; - } - } else { - safeScore[player] += score; - if (safeScore[player] >= maxScore) - break; - System.out.printf(" Sticking with %d\n\n", safeScore[player]); - } - score = 0; - player = (player + 1) % playerCount; - } - System.out.printf("\n\nPlayer %d wins with a score of %d", - player, safeScore[player]); - } -} diff --git a/Task/Power-set/D/power-set.d b/Task/Power-set/D/power-set.d deleted file mode 100644 index 650cc4d63a..0000000000 --- a/Task/Power-set/D/power-set.d +++ /dev/null @@ -1,16 +0,0 @@ -import std.stdio; - -T[][] powerSet(T)(in T[] s) pure nothrow { - auto r = new typeof(return)(1, 0); - foreach (e; s) { - typeof(return) rs; - foreach (x; r) - rs ~= x ~ [e]; - r ~= rs; - } - return r; -} - -void main() { - writeln(powerSet([1, 2, 3])); -} diff --git a/Task/Price-fraction/PL-I/price-fraction.pli b/Task/Price-fraction/PL-I/price-fraction.pli deleted file mode 100644 index 146ee499cd..0000000000 --- a/Task/Price-fraction/PL-I/price-fraction.pli +++ /dev/null @@ -1,14 +0,0 @@ -declare t(20) fixed decimal (3,2) static initial ( - .06, .11, .16, .21, .26, .31, .36, .41, .46, .51, - .56, .61, .66, .71, .76, .81, .86, .91, .96, 1.01); -declare r(20) fixed decimal (3,2) static initial ( - .10, .18, .26, .32, .38, .44, .50, .54, .58, .62, - .66, .70, .74, .78, .82, .86, .90, .94, .98, 1); -declare x float, d fixed decimal (3,2); -declare i fixed binary; - -loop: - do i = 1 to 20; - if x < t(i) then - do; d = r(i); leave loop; end; - end; diff --git a/Task/Price-fraction/REXX/price-fraction.rexx b/Task/Price-fraction/REXX/price-fraction.rexx deleted file mode 100644 index ba1e35c758..0000000000 --- a/Task/Price-fraction/REXX/price-fraction.rexx +++ /dev/null @@ -1,32 +0,0 @@ -/*REXX program to rescale a (decimal fraction) price (0.99 ──► 1.00).*/ -pad=' ' /*for inserting spaces into msg. */ - do j=0 to 1 by .01; if j==0 then j=0.00 /*special case.*/ - say pad 'original price ──►' j pad adjPrice(j) " ◄── adjusted price" - end /*j*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────ADJPRICE subroutine─────────────────*/ -adjPrice: procedure; parse arg ? - select - when ?<0.06 then ?=0.10 - when ?<0.11 then ?=0.18 - when ?<0.16 then ?=0.26 - when ?<0.21 then ?=0.32 - when ?<0.26 then ?=0.38 - when ?<0.31 then ?=0.44 - when ?<0.36 then ?=0.50 - when ?<0.41 then ?=0.54 - when ?<0.46 then ?=0.58 - when ?<0.51 then ?=0.62 - when ?<0.56 then ?=0.66 - when ?<0.61 then ?=0.70 - when ?<0.66 then ?=0.74 - when ?<0.71 then ?=0.78 - when ?<0.76 then ?=0.82 - when ?<0.81 then ?=0.86 - when ?<0.86 then ?=0.90 - when ?<0.91 then ?=0.94 - when ?<0.96 then ?=0.98 - when ?<1.01 then ?=1.00 - otherwise nop - end /*select*/ -return ? diff --git a/Task/Primality-by-trial-division/Scala/primality-by-trial-division.scala b/Task/Primality-by-trial-division/Scala/primality-by-trial-division.scala deleted file mode 100644 index fc177798ce..0000000000 --- a/Task/Primality-by-trial-division/Scala/primality-by-trial-division.scala +++ /dev/null @@ -1 +0,0 @@ -def isPrime(n: Int) = n > 1 && (Iterator.from(2) takeWhile (d => d * d <= n) forall (n % _ != 0)) diff --git a/Task/Quaternion-type/ALGOL-68/quaternion-type.alg b/Task/Quaternion-type/ALGOL-68/quaternion-type.alg deleted file mode 100644 index 68c68eda8b..0000000000 --- a/Task/Quaternion-type/ALGOL-68/quaternion-type.alg +++ /dev/null @@ -1,220 +0,0 @@ -MODE QUAT = STRUCT(REAL re, i, j, k); -MODE QUATERNION = QUAT; -MODE SUBQUAT = UNION(QUAT, #COMPL, # REAL#, INT, [4]REAL, [4]INT # ); - -MODE CLASSQUAT = STRUCT( - PROC (REF QUAT #new#, REAL #re#, REAL #i#, REAL #j#, REAL #k#)REF QUAT new, - PROC (REF QUAT #self#)QUAT conjugate, - PROC (REF QUAT #self#)REAL norm sq, - PROC (REF QUAT #self#)REAL norm, - PROC (REF QUAT #self#)QUAT reciprocal, - PROC (REF QUAT #self#)STRING repr, - PROC (REF QUAT #self#)QUAT neg, - PROC (REF QUAT #self#, SUBQUAT #other#)QUAT add, - PROC (REF QUAT #self#, SUBQUAT #other#)QUAT radd, - PROC (REF QUAT #self#, SUBQUAT #other#)QUAT sub, - PROC (REF QUAT #self#, SUBQUAT #other#)QUAT mul, - PROC (REF QUAT #self#, SUBQUAT #other#)QUAT rmul, - PROC (REF QUAT #self#, SUBQUAT #other#)QUAT div, - PROC (REF QUAT #self#, SUBQUAT #other#)QUAT rdiv, - PROC (REF QUAT #self#)QUAT exp -); - -CLASSQUAT class quat = ( - - # PROC new =#(REF QUAT new, REAL re, i, j, k)REF QUAT: ( - # 'Defaults all parts of quaternion to zero' # - IF new ISNT REF QUAT(NIL) THEN new ELSE HEAP QUAT FI := (re, i, j, k) - ), - - # PROC conjugate =#(REF QUAT self)QUAT: - (re OF self, -i OF self, -j OF self, -k OF self), - - # PROC norm sq =#(REF QUAT self)REAL: - re OF self**2 + i OF self**2 + j OF self**2 + k OF self**2, - - # PROC norm =#(REF QUAT self)REAL: - sqrt((norm sq OF class quat)(self)), - - # PROC reciprocal =#(REF QUAT self)QUAT:( - REAL n2 = (norm sq OF class quat)(self); - QUAT conj = (conjugate OF class quat)(self); - (re OF conj/n2, i OF conj/n2, j OF conj/n2, k OF conj/n2) - ), - - # PROC repr =#(REF QUAT self)STRING: ( - # 'Shorter form of Quaternion as string' # - FILE f; STRING s; associate(f, s); - putf(f, (squat fmt, re OF self>=0, re OF self, - i OF self>=0, i OF self, j OF self>=0, j OF self, k OF self>=0, k OF self)); - close(f); - s - ), - - # PROC neg =#(REF QUAT self)QUAT: - (-re OF self, -i OF self, -j OF self, -k OF self), - - # PROC add =#(REF QUAT self, SUBQUAT other)QUAT: - CASE other IN - (QUAT other): (re OF self + re OF other, i OF self + i OF other, j OF self + j OF other, k OF self + k OF other), - (REAL other): (re OF self + other, i OF self, j OF self, k OF self) - ESAC, - - # PROC radd =#(REF QUAT self, SUBQUAT other)QUAT: - (add OF class quat)(self, other), - - # PROC sub =#(REF QUAT self, SUBQUAT other)QUAT: - CASE other IN - (QUAT other): (re OF self - re OF other, i OF self - i OF other, j OF self - j OF other, k OF self - k OF other), - (REAL other): (re OF self - other, i OF self, j OF self, k OF self) - ESAC, - - # PROC mul =#(REF QUAT self, SUBQUAT other)QUAT: - CASE other IN - (QUAT other):( - re OF self*re OF other - i OF self*i OF other - j OF self*j OF other - k OF self*k OF other, - re OF self*i OF other + i OF self*re OF other + j OF self*k OF other - k OF self*j OF other, - re OF self*j OF other - i OF self*k OF other + j OF self*re OF other + k OF self*i OF other, - re OF self*k OF other + i OF self*j OF other - j OF self*i OF other + k OF self*re OF other - ), - (REAL other): ( re OF self * other, i OF self * other, j OF self * other, k OF self * other) - ESAC, - - # PROC rmul =#(REF QUAT self, SUBQUAT other)QUAT: - CASE other IN - (QUAT other): (mul OF class quat)(LOC QUAT := other, self), - (REAL other): (mul OF class quat)(self, other) - ESAC, - - # PROC div =#(REF QUAT self, SUBQUAT other)QUAT: - CASE other IN - (QUAT other): (mul OF class quat)(self, (reciprocal OF class quat)(LOC QUAT := other)), - (REAL other): (mul OF class quat)(self, 1/other) - ESAC, - - # PROC rdiv =#(REF QUAT self, SUBQUAT other)QUAT: - CASE other IN - (QUAT other): (div OF class quat)(LOC QUAT := other, self), - (REAL other): (div OF class quat)(LOC QUAT := (other, 0, 0, 0), self) - ESAC, - - # PROC exp =#(REF QUAT self)QUAT: ( - QUAT fac := self; - QUAT sum := 1.0 + fac; - FOR i FROM 2 WHILE ABS(fac + small real) /= small real DO - VOID(sum +:= (fac *:= self / REAL(i))) - OD; - sum - ) -); - -FORMAT real fmt = $g(-0, 4)$; -FORMAT signed fmt = $b("+", "")f(real fmt)$; - -FORMAT quat fmt = $f(real fmt)"+"f(real fmt)"i+"f(real fmt)"j+"f(real fmt)"k"$; -FORMAT squat fmt = $f(signed fmt)f(signed fmt)"i"f(signed fmt)"j"f(signed fmt)"k"$; - -PRIO INIT = 1; -OP INIT = (REF QUAT new)REF QUAT: new := (0, 0, 0, 0); -OP INIT = (REF QUAT new, []REAL rijk)REF QUAT: - (new OF class quat)(LOC QUAT := new, rijk[1], rijk[2], rijk[3], rijk[4]); - -OP + = (QUAT q)QUAT: q, - - = (QUAT q)QUAT: (neg OF class quat)(LOC QUAT := q), - CONJ = (QUAT q)QUAT: (conjugate OF class quat)(LOC QUAT := q), - ABS = (QUAT q)REAL: (norm OF class quat)(LOC QUAT := q), - REPR = (QUAT q)STRING: (repr OF class quat)(LOC QUAT := q); -# missing: Diadic: I, J, K END # - -OP +:= = (REF QUAT a, QUAT b)QUAT: a:=( add OF class quat)(a, b), - +:= = (REF QUAT a, REAL b)QUAT: a:=( add OF class quat)(a, b), - +=: = (QUAT a, REF QUAT b)QUAT: b:=(radd OF class quat)(b, a), - +=: = (REAL a, REF QUAT b)QUAT: b:=(radd OF class quat)(b, a); -# missing: Worthy PLUSAB, PLUSTO for SHORT/LONG INT REAL & COMPL # - -OP -:= = (REF QUAT a, QUAT b)QUAT: a:=( sub OF class quat)(a, b), - -:= = (REF QUAT a, REAL b)QUAT: a:=( sub OF class quat)(a, b); -# missing: Worthy MINUSAB for SHORT/LONG INT REAL & COMPL # - -PRIO *=: = 1, /=: = 1; -OP *:= = (REF QUAT a, QUAT b)QUAT: a:=( mul OF class quat)(a, b), - *:= = (REF QUAT a, REAL b)QUAT: a:=( mul OF class quat)(a, b), - *=: = (QUAT a, REF QUAT b)QUAT: b:=(rmul OF class quat)(b, a), - *=: = (REAL a, REF QUAT b)QUAT: b:=(rmul OF class quat)(b, a); -# missing: Worthy TIMESAB, TIMESTO for SHORT/LONG INT REAL & COMPL # - -OP /:= = (REF QUAT a, QUAT b)QUAT: a:=( div OF class quat)(a, b), - /:= = (REF QUAT a, REAL b)QUAT: a:=( div OF class quat)(a, b), - /=: = (QUAT a, REF QUAT b)QUAT: b:=(rdiv OF class quat)(b, a), - /=: = (REAL a, REF QUAT b)QUAT: b:=(rdiv OF class quat)(b, a); -# missing: Worthy OVERAB, OVERTO for SHORT/LONG INT REAL & COMPL # - -OP + = (QUAT a, b)QUAT: ( add OF class quat)(LOC QUAT := a, b), - + = (QUAT a, REAL b)QUAT: ( add OF class quat)(LOC QUAT := a, b), - + = (REAL a, QUAT b)QUAT: (radd OF class quat)(LOC QUAT := b, a); - -OP - = (QUAT a, b)QUAT: ( sub OF class quat)(LOC QUAT := a, b), - - = (QUAT a, REAL b)QUAT: ( sub OF class quat)(LOC QUAT := a, b), - - = (REAL a, QUAT b)QUAT:-( sub OF class quat)(LOC QUAT := b, a); - -OP * = (QUAT a, b)QUAT: ( mul OF class quat)(LOC QUAT := a, b), - * = (QUAT a, REAL b)QUAT: ( mul OF class quat)(LOC QUAT := a, b), - * = (REAL a, QUAT b)QUAT: (rmul OF class quat)(LOC QUAT := b, a); - -OP / = (QUAT a, b)QUAT: ( div OF class quat)(LOC QUAT := a, b), - / = (QUAT a, REAL b)QUAT: ( div OF class quat)(LOC QUAT := a, b), - / = (REAL a, QUAT b)QUAT: ( div OF class quat)(LOC QUAT := b, 1/a); - -PROC quat exp = (QUAT q)QUAT: (exp OF class quat)(LOC QUAT := q); -# missing: quat arc{sin, cos, tan}h, log, exp, ln etc END # - -test:( - REAL r = 7; - QUAT q = (1, 2, 3, 4), - q1 = (2, 3, 4, 5), - q2 = (3, 4, 5, 6); - - printf(( - $"r = " f(real fmt)l$, r, - $"q = " f(quat fmt)l$, q, - $"q1 = " f(quat fmt)l$, q1, - $"q2 = " f(quat fmt)l$, q2, - $"ABS q = " f(real fmt)", "$, ABS q, - $"ABS q1 = " f(real fmt)", "$, ABS q1, - $"ABS q2 = " f(real fmt)l$, ABS q2, - $"-q = " f(quat fmt)l$, -q, - $"CONJ q = " f(quat fmt)l$, CONJ q, - $"r + q = " f(quat fmt)l$, r + q, - $"q + r = " f(quat fmt)l$, q + r, - $"q1 + q2 = "f(quat fmt)l$, q1 + q2, - $"q2 + q1 = "f(quat fmt)l$, q2 + q1, - $"q * r = " f(quat fmt)l$, q * r, - $"r * q = " f(quat fmt)l$, r * q, - $"q1 * q2 = "f(quat fmt)l$, q1 * q2, - $"q2 * q1 = "f(quat fmt)l$, q2 * q1 - )); - -CO - $"ASSERT q1 * q2 != q2 * q1 = "f(quat fmt)l$, ASSERT q1 * q2 != q2 * q1, $l$); -END CO - - QUAT i=(0, 1, 0, 0), - j=(0, 0, 1, 0), - k=(0, 0, 0, 1); - - printf(( - $"i*i = " f(quat fmt)l$, i*i, - $"j*j = " f(quat fmt)l$, j*j, - $"k*k = " f(quat fmt)l$, k*k, - $"i*j*k = " f(quat fmt)l$, i*j*k, - $"q1 / q2 = " f(quat fmt)l$, q1 / q2, - $"q1 / q2 * q2 = "f(quat fmt)l$, q1 / q2 * q2, - $"q2 * q1 / q2 = "f(quat fmt)l$, q2 * q1 / q2, - $"1/q1 * q1 = " f(quat fmt)l$, 1.0/q1 * q1, - $"q1 / q1 = " f(quat fmt)l$, q1 / q1, - $"quat exp(pi * i) = " f(quat fmt)l$, quat exp(pi * i), - $"quat exp(pi * j) = " f(quat fmt)l$, quat exp(pi * j), - $"quat exp(pi * i) = " f(quat fmt)l$, quat exp(pi * k) - )); - print((REPR(-q1*q2), ", ", REPR(-q2*q1), new line)) -) diff --git a/Task/Quine/Mathematica/quine.math b/Task/Quine/Mathematica/quine.math deleted file mode 100644 index c01cbc8f32..0000000000 --- a/Task/Quine/Mathematica/quine.math +++ /dev/null @@ -1 +0,0 @@ -a="Print[\"a=\",InputForm[a],\";\",a]";Print["a=",InputForm[a],";",a] diff --git a/Task/Read-a-file-line-by-line/OCaml/read-a-file-line-by-line.ocaml b/Task/Read-a-file-line-by-line/OCaml/read-a-file-line-by-line.ocaml deleted file mode 100644 index ff0602a5e2..0000000000 --- a/Task/Read-a-file-line-by-line/OCaml/read-a-file-line-by-line.ocaml +++ /dev/null @@ -1,9 +0,0 @@ -let () = - let ic = open_in "input.txt" in - try - while true do - let line = input_line ic in - print_endline line - done - with End_of_file -> - close_in ic diff --git a/Task/Read-a-file-line-by-line/PHP/read-a-file-line-by-line.php b/Task/Read-a-file-line-by-line/PHP/read-a-file-line-by-line.php deleted file mode 100644 index 91cfd0210d..0000000000 --- a/Task/Read-a-file-line-by-line/PHP/read-a-file-line-by-line.php +++ /dev/null @@ -1,6 +0,0 @@ - - -// The methods need to be declared somewhere -@interface Dummy : NSObject { } -- (void)grill; -- (void)ding:(NSString *)s; -@end - -@interface Example : NSObject { } -- (void)foo; -- (void)bar; -@end - -@implementation Example -- (void)foo { - NSLog(@"this is foo"); -} -- (void)bar { - NSLog(@"this is bar"); -} -- (void)forwardInvocation:(NSInvocation *)inv { - NSLog(@"tried to handle unknown method %@", NSStringFromSelector([inv selector])); - unsigned n = [[inv methodSignature] numberOfArguments]; - unsigned i; - for (i = 0; i < n-2; i++) { // first two arguments are the object and selector - id arg; // we assume that all arguments are objects - [inv getArgument:&arg atIndex:i+2]; - NSLog(@"argument #%u: %@", i, arg); - } -} -// forwardInvocation: does not work without methodSignatureForSelector: -- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { - int numArgs = [[NSStringFromSelector(aSelector) componentsSeparatedByString:@":"] count] - 1; - // we assume that all arguments are objects - // The type encoding is "v@:@@@...", where "v" is the return type, void - // "@" is the receiver, object type; ":" is the selector of the current method; - // and each "@" after corresponds to an object argument - return [NSMethodSignature signatureWithObjCTypes: - [[@"v@:" stringByPaddingToLength:numArgs+3 withString:@"@" startingAtIndex:0] UTF8String]]; -} -@end - -int main() -{ - NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; - - id example = [[Example alloc] init]; - - [example foo]; // prints "this is foo" - [example bar]; // prints "this is bar" - [example grill]; // prints "tried to handle unknown method grill" - [example ding:@"dong"]; // prints "tried to handle unknown method ding:" - // prints "argument #0: dong" - [example release]; - - [pool release]; - - return 0; -} diff --git a/Task/Return-multiple-values/C/return-multiple-values.c b/Task/Return-multiple-values/C/return-multiple-values.c deleted file mode 100644 index 3792fb5c90..0000000000 --- a/Task/Return-multiple-values/C/return-multiple-values.c +++ /dev/null @@ -1,39 +0,0 @@ -#include - -typedef struct{ - int integer; - float decimal; - char letter; - char string[100]; - double bigDecimal; -}Composite; - -typedef union{ - int num; - char letter; -}Zip; - -Composite example() -{ - Composite C = {1,2.3,'a',"Hello World",45.678}; - return C; -} - -Zip example2() -{ - Zip r; - r.num = 99; - r.letter = 'C'; - return r; -} - -int main() -{ - Composite C = example(); - Zip rar = example2(); - - printf("Values from a function returning a structure : { %d, %f, %c, %s, %f}",C.integer, C.decimal,C.letter,C.string,C.bigDecimal); - printf("\n\nValues from a function returning a union : { %d, %c}",rar.num,rar.letter); - - return 0; -} diff --git a/Task/Rock-paper-scissors/D/rock-paper-scissors.d b/Task/Rock-paper-scissors/D/rock-paper-scissors.d deleted file mode 100644 index f0bccabaf5..0000000000 --- a/Task/Rock-paper-scissors/D/rock-paper-scissors.d +++ /dev/null @@ -1,55 +0,0 @@ -import std.stdio, std.random, std.string, std.array; - -enum string[] order = ["rock", "paper", "scissors"]; -int[string] choiceFrequency; // mutable - -immutable(string[string]) whatBeats; -nothrow pure static this() { - whatBeats = ["paper": "scissors", - "scissors": "rock", - "rock": "paper"]; -} - -string checkWinner(in string a, in string b) pure nothrow { - if (b == whatBeats[a]) - return b; - else if (a == whatBeats[b]) - return a; - return ""; -} - -string getRandomChoice() /*nothrow*/ { - //if (choiceFrequency.empty) - if (choiceFrequency.length == 0) - return order[uniform(0, $)]; - const choices = choiceFrequency.keys; - const probabilities = choiceFrequency.values; - return whatBeats[choices[dice(probabilities)]]; -} - -void main() { - writeln("Rock-paper-scissors game"); - while (true) { - write("Your choice: "); - immutable string humanChoice = readln().strip().toLower(); - if (humanChoice.empty) - break; - if (humanChoice !in whatBeats) { - writeln("Wrong input: ", humanChoice); - continue; - } - - immutable compChoice = getRandomChoice(); - write("Computer picked ", compChoice, ", "); - - // Don't register the player choice until after - // the computer has made its choice. - choiceFrequency[humanChoice]++; - - immutable winner = checkWinner(humanChoice, compChoice); - if (winner.empty) - writeln("nobody wins!"); - else - writeln(winner, " wins!"); - } -} diff --git a/Task/Roman-numerals-Decode/Common-Lisp/roman-numerals-decode.lisp b/Task/Roman-numerals-Decode/Common-Lisp/roman-numerals-decode.lisp deleted file mode 100644 index de01944593..0000000000 --- a/Task/Roman-numerals-Decode/Common-Lisp/roman-numerals-decode.lisp +++ /dev/null @@ -1,9 +0,0 @@ -(defun parse-roman (r) - (loop for l on (map 'list (lambda (c) - (getf '(#\I 1 #\V 5 #\X 10 #\L 50 #\C 100 #\D 500 #\M 1000) c)) - (string-upcase r)) - sum (let ((a (first l)) (b (second l))) - (if (and b (< a b)) (- a) a)))) -;; test code -(dolist (r '("MCMXC" "MDCLXVI" "MMVIII")) - (format t "~a: ~d~%" r (parse-roman r))) diff --git a/Task/Roman-numerals-Decode/Java/roman-numerals-decode.java b/Task/Roman-numerals-Decode/Java/roman-numerals-decode.java deleted file mode 100644 index d0e5432d5d..0000000000 --- a/Task/Roman-numerals-Decode/Java/roman-numerals-decode.java +++ /dev/null @@ -1,37 +0,0 @@ -public class Roman { - private static int decodeSingle(char letter) { - switch(letter) { - case 'M': return 1000; - case 'D': return 500; - case 'C': return 100; - case 'L': return 50; - case 'X': return 10; - case 'V': return 5; - case 'I': return 1; - default: return 0; - } - } - public static int decode(String roman) { - int result = 0; - String uRoman = roman.toUpperCase(); //case-insensitive - for(int i = 0;i < uRoman.length() - 1;i++) {//loop over all but the last character - //if this character has a lower value than the next character - if (decodeSingle(uRoman.charAt(i)) < decodeSingle(uRoman.charAt(i+1))) { - //subtract it - result -= decodeSingle(uRoman.charAt(i)); - } else { - //add it - result += decodeSingle(uRoman.charAt(i)); - } - } - //decode the last character, which is always added - result += decodeSingle(uRoman.charAt(uRoman.length()-1)); - return result; - } - - public static void main(String[] args) { - System.out.println(decode("MCMXC")); //1990 - System.out.println(decode("MMVIII")); //2008 - System.out.println(decode("MDCLXVI")); //1666 - } -} diff --git a/Task/Roman-numerals-Encode/Erlang/roman-numerals-encode.erl b/Task/Roman-numerals-Encode/Erlang/roman-numerals-encode.erl deleted file mode 100644 index d5d4937b0d..0000000000 --- a/Task/Roman-numerals-Encode/Erlang/roman-numerals-encode.erl +++ /dev/null @@ -1,20 +0,0 @@ --module(roman). --export([to_roman/1]). - -to_roman(0) -> []; -to_roman(X) when X >= 1000 -> [$M | to_roman(X - 1000)]; -to_roman(X) when X >= 100 -> - digit(X div 100, $C, $D, $M) ++ to_roman(X rem 100); -to_roman(X) when X >= 10 -> - digit(X div 10, $X, $L, $C) ++ to_roman(X rem 10); -to_roman(X) when X >= 1 -> digit(X, $I, $V, $X). - -digit(1, X, _, _) -> [X]; -digit(2, X, _, _) -> [X, X]; -digit(3, X, _, _) -> [X, X, X]; -digit(4, X, Y, _) -> [X, Y]; -digit(5, _, Y, _) -> [Y]; -digit(6, X, Y, _) -> [Y, X]; -digit(7, X, Y, _) -> [Y, X, X]; -digit(8, X, Y, _) -> [Y, X, X, X]; -digit(9, X, _, Z) -> [X, Z]. diff --git a/Task/Roman-numerals-Encode/Java/roman-numerals-encode.java b/Task/Roman-numerals-Encode/Java/roman-numerals-encode.java deleted file mode 100644 index 81508f53e1..0000000000 --- a/Task/Roman-numerals-Encode/Java/roman-numerals-encode.java +++ /dev/null @@ -1,41 +0,0 @@ -public class RN { - - enum Numeral { - I(1), IV(4), V(5), IX(9), X(10), XL(40), L(50), XC(90), C(100), CD(400), D(500), CM(900), M(1000); - int weight; - - Numeral(int weight) { - this.weight = weight; - } - }; - - public static String roman(long n) { - - if( n <= 0) { - throw new IllegalArgumentException(); - } - - StringBuilder buf = new StringBuilder(); - - final Numeral[] values = Numeral.values(); - for (int i = values.length - 1; i >= 0; i--) { - while (n >= values[i].weight) { - buf.append(values[i]); - n -= values[i].weight; - } - } - return buf.toString(); - } - - public static void test(long n) { - System.out.println(n + " = " + roman(n)); - } - - public static void main(String[] args) { - test(1999); - test(25); - test(944); - test(0); - } - -} diff --git a/Task/Roman-numerals-Encode/Racket/roman-numerals-encode.rkt b/Task/Roman-numerals-Encode/Racket/roman-numerals-encode.rkt deleted file mode 100644 index b796d884db..0000000000 --- a/Task/Roman-numerals-Encode/Racket/roman-numerals-encode.rkt +++ /dev/null @@ -1,15 +0,0 @@ -#lang racket -(define (encode/roman number) - (cond ((>= number 1000) (string-append "M" (encode/roman (- number 1000)))) - ((>= number 900) (string-append "CM" (encode/roman (- number 900)))) - ((>= number 500) (string-append "D" (encode/roman (- number 500)))) - ((>= number 400) (string-append "CD" (encode/roman (- number 400)))) - ((>= number 100) (string-append "C" (encode/roman (- number 100)))) - ((>= number 90) (string-append "XC" (encode/roman (- number 90)))) - ((>= number 50) (string-append "L" (encode/roman (- number 50)))) - ((>= number 40) (string-append "XL" (encode/roman (- number 40)))) - ((>= number 10) (string-append "X" (encode/roman (- number 10)))) - ((>= number 5) (string-append "V" (encode/roman (- number 5)))) - ((>= number 4) (string-append "IV" (encode/roman (- number 4)))) - ((>= number 1) (string-append "I" (encode/roman (- number 1)))) - (else ""))) diff --git a/Task/Roots-of-a-quadratic-function/REXX/roots-of-a-quadratic-function.rexx b/Task/Roots-of-a-quadratic-function/REXX/roots-of-a-quadratic-function.rexx deleted file mode 100644 index 8d1efbced1..0000000000 --- a/Task/Roots-of-a-quadratic-function/REXX/roots-of-a-quadratic-function.rexx +++ /dev/null @@ -1,36 +0,0 @@ -/*REXX program finds the roots (may be complex) of a quadratic function.*/ -numeric digits 120 /*use enough digits for extremes.*/ -parse arg a b c . /*get specified arguments: A B C*/ -a=a/1; b=b/1; c=c/1 /*normalize the three numbers. */ -say 'a=' a /*show value of A. */ -say 'b=' b /* " " " B. */ -say 'c=' c /* " " " C. */ -call quadratic a b c /*solve the quadratic function. */ -numeric digits sqrt(digits())%1 /*reduce digits for human beans. */ -r1=r1/1 /*normalize to the new digits. */ -r2=r2/1 /* " " " " " */ -if r1j\=0 then r1=r1 || left('+',r1j>0)(r1j/1)"i" /*handle complex num.*/ -if r2j\=0 then r2=r2 || left('+',r2j>0)(r2j/1)"i" /* " " " */ -say -say 'root1=' r1 /*show 1st root (may be complex).*/ -say 'root2=' r2 /* " 2nd " " " " */ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────QUADRATIC subroutine────────────────*/ -quadratic: parse arg aa bb cc . -?=sqrt(bb**2-4*aa*cc) /*compute sqrt (might be complex)*/ -aa2=1 / (aa+aa) /*compute reciprocal of 2*aa */ -if right(?,1)=='i' then do /*are the roots complex? */ - ?i=left(?,length(?)-1) - r1=-bb*aa2; r2=r1; r1j=?i*aa2; r2j=-?i*aa2 - end - else do - r1=(-bb+?)*aa2; r2=(-bb-?)*aa2; r1j=0; r2j=0 - end -return -/*──────────────────────────────────SQRT subroutine─────────────────────*/ -sqrt: procedure; parse arg x,f; if x=0 then return 0; d=digits() -numeric digits 11; g=.sqrtG(); do j=0 while p>9; m.j=p; p=p%2+1; end - do k=j+5 to 0 by -1; if m.k>11 then numeric digits m.k; g=.5*(g+x/g); end; - numeric digits d;return (g/1)i -.sqrtG: i=left('i',x<0); numeric form; m.=11; p=d+d%4+2 - parse value format(x,2,1,,0) 'E0' with g 'E' _ .; return g*.5'E'_%2 diff --git a/Task/Rot-13/AutoHotkey/rot-13.ahk b/Task/Rot-13/AutoHotkey/rot-13.ahk deleted file mode 100644 index bc06461dc6..0000000000 --- a/Task/Rot-13/AutoHotkey/rot-13.ahk +++ /dev/null @@ -1,28 +0,0 @@ -Str0=Hello, This is a sample text with 1 2 3 or other digits!@#$^&*()-_= -Str1 := Rot13(Str0) -Str2 := Rot13(Str1) -MsgBox % Str0 "`n" Str1 "`n" Str2 - -Rot13(string) -{ - Loop Parse, string - { - char := Asc(A_LoopField) - ; o is 'A' code if it is an uppercase letter, and 'a' code if it is a lowercase letter - o := Asc("A") * (Asc("A") <= char && char <= Asc("Z")) + Asc("a") * (Asc("a") <= char && char <= Asc("z")) - If (o > 0) - { - ; Set between 0 and 25, add rotation factor, modulus alphabet size - char := Mod(char - o + 13, 26) - ; Transform back to char, upper or lower - char := Chr(char + o) - } - Else - { - ; Non alphabetic, unchanged - char := A_LoopField - } - rStr .= char - } - Return rStr -} diff --git a/Task/Rot-13/BASIC/rot-13.basic b/Task/Rot-13/BASIC/rot-13.basic deleted file mode 100644 index 5bf272fe38..0000000000 --- a/Task/Rot-13/BASIC/rot-13.basic +++ /dev/null @@ -1,17 +0,0 @@ -CLS -INPUT "Enter a string: ", s$ -ans$ = "" -FOR a = 1 TO LEN(s$) - letter$ = MID$(s$, a, 1) - IF letter$ >= "A" AND letter$ <= "Z" THEN - char$ = CHR$(ASC(letter$) + 13) - IF char$ > "Z" THEN char$ = CHR$(ASC(char$) - 26) - ELSEIF letter$ >= "a" AND letter$ <= "z" THEN - char$ = CHR$(ASC(letter$) + 13) - IF char$ > "z" THEN char$ = CHR$(ASC(char$) - 26) - ELSE - char$ = letter$ - END IF - ans$ = ans$ + char$ -NEXT a -PRINT ans$ diff --git a/Task/Rot-13/C/rot-13.c b/Task/Rot-13/C/rot-13.c deleted file mode 100644 index a4ffc76630..0000000000 --- a/Task/Rot-13/C/rot-13.c +++ /dev/null @@ -1,44 +0,0 @@ -#include -#include -#include - -#define MAXLINE 1024 - -char *rot13(char *s) -{ - char *p=s; - int upper; - - while(*p) { - upper=toupper(*p); - if(upper>='A' && upper<='M') *p+=13; - else if(upper>='N' && upper<='Z') *p-=13; - ++p; - } - return s; -} - -void rot13file(FILE *fp) -{ - static char line[MAXLINE]; - while(fgets(line, MAXLINE, fp)>0) fputs(rot13(line), stdout); -} - -int main(int argc, char *argv[]) -{ - int n; - FILE *fp; - - if(argc>1) { - for(n=1; n - doEncode(string:substr(S, 2), string:substr(S, 1, 1), 1, []). - -doEncode([], CurrChar, Count, R) -> - R ++ integer_to_list(Count) ++ CurrChar; -doEncode(S, CurrChar, Count, R) -> - NextChar = string:substr(S, 1, 1), - if - NextChar == CurrChar -> - doEncode(string:substr(S, 2), CurrChar, Count + 1, R); - true -> - doEncode(string:substr(S, 2), NextChar, 1, - R ++ integer_to_list(Count) ++ CurrChar) - end. - -decode(S) -> - doDecode(string:substr(S, 2), string:substr(S, 1, 1), []). - -doDecode([], _, R) -> - R; -doDecode(S, CurrString, R) -> - NextChar = string:substr(S, 1, 1), - IsInt = erlang:is_integer(catch(erlang:list_to_integer(NextChar))), - if - IsInt -> - doDecode(string:substr(S, 2), CurrString ++ NextChar, R); - true -> - doDecode(string:substr(S, 2), [], - R ++ string:copies(NextChar, list_to_integer(CurrString))) - end. - -rle_test_() -> - PreEncoded = - "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW", - Expected = "12W1B12W3B24W1B14W", - [ - ?_assert(encode(PreEncoded) =:= Expected), - ?_assert(decode(Expected) =:= PreEncoded), - ?_assert(decode(encode(PreEncoded)) =:= PreEncoded) - ]. diff --git a/Task/Set-of-real-numbers/D/set-of-real-numbers.d b/Task/Set-of-real-numbers/D/set-of-real-numbers.d deleted file mode 100644 index bcdda17e71..0000000000 --- a/Task/Set-of-real-numbers/D/set-of-real-numbers.d +++ /dev/null @@ -1,61 +0,0 @@ -struct Set(T) { - const pure nothrow bool delegate(in T) contains; - - bool opIn_r(in T x) const pure nothrow { - return contains(x); - } - - Set opBinary(string op)(in Set set) - const pure nothrow if (op == "+" || op == "-") { - static if (op == "+") - return Set(x => contains(x) || set.contains(x)); - else - return Set(x => contains(x) && !set.contains(x)); - } - - Set intersection(in Set set) const pure nothrow { - return Set(x => contains(x) && set.contains(x)); - } -} - -unittest { // Test union. - alias DSet = Set!double; - const s = DSet(x => 0.0 < x && x <= 1.0) + - DSet(x => 0.0 <= x && x < 2.0); - assert(0.0 in s); - assert(1.0 in s); - assert(2.0 !in s); -} - -unittest { // Test difference. - alias DSet = Set!double; - const s1 = DSet(x => 0.0 <= x && x < 3.0) - - DSet(x => 0.0 < x && x < 1.0); - assert(0.0 in s1); - assert(0.5 !in s1); - assert(1.0 in s1); - assert(2.0 in s1); - - const s2 = DSet(x => 0.0 <= x && x < 3.0) - - DSet(x => 0.0 <= x && x <= 1.0); - assert(0.0 !in s2); - assert(1.0 !in s2); - assert(2.0 in s2); - - const s3 = DSet(x => 0 <= x && x <= double.infinity) - - DSet(x => 1.0 <= x && x <= 2.0); - assert(0.0 in s3); - assert(1.5 !in s3); - assert(3.0 in s3); -} - -unittest { // Test intersection. - alias DSet = Set!double; - const s = DSet(x => 0.0 <= x && x < 2.0).intersection( - DSet(x => 1.0 < x && x <= 2.0)); - assert(0.0 !in s); - assert(1.0 !in s); - assert(2.0 !in s); -} - -void main() {} diff --git a/Task/Shell-one-liner/Scala/shell-one-liner.scala b/Task/Shell-one-liner/Scala/shell-one-liner.scala deleted file mode 100644 index f35ada5371..0000000000 --- a/Task/Shell-one-liner/Scala/shell-one-liner.scala +++ /dev/null @@ -1,2 +0,0 @@ -C:\>scala -e "println(\"Hello\")" -Hello diff --git a/Task/Show-the-epoch/UNIX-Shell/show-the-epoch.sh b/Task/Show-the-epoch/UNIX-Shell/show-the-epoch.sh deleted file mode 100644 index fab910f3c4..0000000000 --- a/Task/Show-the-epoch/UNIX-Shell/show-the-epoch.sh +++ /dev/null @@ -1,2 +0,0 @@ -$ date -ur 0 -Thu Jan 1 00:00:00 UTC 1970 diff --git a/Task/Sierpinski-triangle-Graphical/Mathematica/sierpinski-triangle-graphical.math b/Task/Sierpinski-triangle-Graphical/Mathematica/sierpinski-triangle-graphical.math deleted file mode 100644 index 9fa00fd02f..0000000000 --- a/Task/Sierpinski-triangle-Graphical/Mathematica/sierpinski-triangle-graphical.math +++ /dev/null @@ -1,8 +0,0 @@ -Sierpinski[n_] :=Nest[Flatten[Table[{{ - #[[i, 1]], (#[[i, 1]] + #[[i, 2]])/2, (#[[i, 1]] + #[[i, 3]])/ - 2}, {(#[[i, 1]] + #[[i, 2]])/2, #[[i, - 2]], (#[[i, 2]] + #[[i, 3]])/2}, {(#[[i, 1]] + #[[i, 3]])/ - 2, (#[[i, 2]] + #[[i, 3]])/2, #[[i, 3]]}}, {i, Length[#]}], - 1] &, {{{0, 0}, {1/2, 1}, {1, 0}}}, n] - -Show[Graphics[{Opacity[1], Black, Map[Polygon, Sierpinski[8], 1]}, AspectRatio -> 1]] diff --git a/Task/Sierpinski-triangle-Graphical/Racket/sierpinski-triangle-graphical.rkt b/Task/Sierpinski-triangle-Graphical/Racket/sierpinski-triangle-graphical.rkt deleted file mode 100644 index c5c8af8b95..0000000000 --- a/Task/Sierpinski-triangle-Graphical/Racket/sierpinski-triangle-graphical.rkt +++ /dev/null @@ -1,12 +0,0 @@ -#lang racket -(require 2htdp/image) -(define (sierpinski n) - (if (zero? n) - (triangle 2 'solid 'red) - (let ([t (sierpinski (- n 1))]) - (freeze (above t (beside t t)))))) -;; the following will show the graphics if run in DrRacket -(sierpinski 8) -;; or use this to dump the image into a file, shown on the right -(require file/convertible) -(display-to-file (convert (sierpinski 8) 'png-bytes) "sierpinski.png") diff --git a/Task/Singleton/Racket/singleton.rkt b/Task/Singleton/Racket/singleton.rkt deleted file mode 100644 index 80b86f4895..0000000000 --- a/Task/Singleton/Racket/singleton.rkt +++ /dev/null @@ -1,9 +0,0 @@ -#lang racket - -(provide instance) - -(define singleton% - (class object% - (super-new))) - -(define instance (new singleton%)) diff --git a/Task/Sort-using-a-custom-comparator/D/sort-using-a-custom-comparator.d b/Task/Sort-using-a-custom-comparator/D/sort-using-a-custom-comparator.d deleted file mode 100644 index f662e53afc..0000000000 --- a/Task/Sort-using-a-custom-comparator/D/sort-using-a-custom-comparator.d +++ /dev/null @@ -1,8 +0,0 @@ -import std.stdio, std.string, std.algorithm, std.typecons; - -void main() { - "here are Some sample strings to be sorted" - .split - .schwartzSort!q{ tuple(-a.length, a.toUpper) } - .writeln; -} diff --git a/Task/Sorting-algorithms-Bogosort/Java/sorting-algorithms-bogosort.java b/Task/Sorting-algorithms-Bogosort/Java/sorting-algorithms-bogosort.java deleted file mode 100644 index 15e0f2f869..0000000000 --- a/Task/Sorting-algorithms-Bogosort/Java/sorting-algorithms-bogosort.java +++ /dev/null @@ -1,24 +0,0 @@ -import java.util.Collections; -import java.util.List; -import java.util.Iterator; - -public class Bogosort { - private static > boolean isSorted(List list) { - if (list.isEmpty()) - return true; - Iterator it = list.iterator(); - T last = it.next(); - while (it.hasNext()) { - T current = it.next(); - if (last.compareTo(current) > 0) - return false; - last = current; - } - return true; - } - - public static > void bogoSort(List list) { - while (!isSorted(list)) - Collections.shuffle(list); - } -} diff --git a/Task/Sorting-algorithms-Counting-sort/NetRexx/sorting-algorithms-counting-sort.netrexx b/Task/Sorting-algorithms-Counting-sort/NetRexx/sorting-algorithms-counting-sort.netrexx deleted file mode 100644 index 9765394601..0000000000 --- a/Task/Sorting-algorithms-Counting-sort/NetRexx/sorting-algorithms-counting-sort.netrexx +++ /dev/null @@ -1,69 +0,0 @@ -/* NetRexx */ -options replace format comments java crossref savelog symbols binary - -import java.util.List - -icounts = [int - - 1, 3, 6, 2, 7, 13, 20, 12, 21, 11 - - , 22, 10, 23, 9, 24, 8, 25, 43, 62, 42 - - , 63, 41, 18, 42, 17, 43, 16, 44, 15, 45 - - , 14, 46, 79, 113, 78, 114, 77, 39, 78, 38 - -] -scounts = int[icounts.length] - -System.arraycopy(icounts, 0, scounts, 0, icounts.length) -lists = [ - - icounts - - , countingSort(scounts) - -] - -loop ln = 0 to lists.length - 1 - cl = lists[ln] - rep = Rexx('') - loop ct = 0 to cl.length - 1 - rep = rep cl[ct] - end ct - say '['rep.strip.changestr(' ', ',')']' - end ln - -return - -method getMin(array = int[]) public constant binary returns int - - amin = Integer.MAX_VALUE - loop x_ = 0 to array.length - 1 - if array[x_] < amin then - amin = array[x_] - end x_ - - return amin - -method getMax(array = int[]) public constant binary returns int - - amax = Integer.MIN_VALUE - loop x_ = 0 to array.length - 1 - if array[x_] > amax then - amax = array[x_] - end x_ - - return amax - -method countingSort(array = int[], amin = getMin(array), amax = getMax(array)) public constant binary returns int[] - - count = int[amax - amin + 1] - loop nr = 0 to array.length - 1 - numbr = array[nr] - count[numbr - amin] = count[numbr - amin] + 1 - end nr - - z_ = 0 - - loop i_ = amin to amax - loop label count while count[i_ - amin] > 0 - array[z_] = i_ - z_ = z_ + 1 - count[i_ - amin] = count[i_ - amin] - 1 - end count - end i_ - - return array diff --git a/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort.rexx b/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort.rexx deleted file mode 100644 index 3e33938a33..0000000000 --- a/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort.rexx +++ /dev/null @@ -1,56 +0,0 @@ -/*REXX program sorts an array using the heapsort method. */ -call gen@ /*generate the array elements. */ -call show@ 'before sort' /*show the before array elements*/ -call heapSort highItem /*invoke the heap sort. */ -call show@ ' after sort' /*show tge after array elements*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────HEAPSORT subroutine─────────────────*/ -heapSort: procedure expose @.; parse arg n - - do j=n%2 by -1 to 1 - call shuffle j,n - end /*j*/ - do n=n by -1 to 2 - _=@.1; @.1=@.n; @.n=_; call shuffle 1,n - end /*n*/ -return -/*──────────────────────────────────SHUFFLE subroutine──────────────────*/ -shuffle: procedure expose @.; parse arg i,n; _=@.i - - do while i+i<=n - j=i+i; k=j+1 - if k<=n & @.k>@.j then j=k - if _>=@.j then leave - @.i=@.j; i=j - end /*while i+i<=n*/ -@.i=_ -return -/*──────────────────────────────────GEN@ subroutine─────────────────────*/ -gen@: @.= /*assign default value for array.*/ -@.1 ='---letters of the modern Greek Alphabet---' ; @.14='mu' -@.2 ='==========================================' ; @.15='nu' -@.3 ='alpha' ; @.16='xi' -@.4 ='beta' ; @.17='omicron' -@.5 ='gamma' ; @.18='pi' -@.6 ='delta' ; @.19='rho' -@.7 ='epsilon' ; @.20='sigma' -@.8 ='zeta' ; @.21='tau' -@.9 ='eta' ; @.22='upsilon' -@.10='theta' ; @.23='phi' -@.11='iota' ; @.24='chi' -@.12='kappa' ; @.25='psi' -@.13='lambda' ; @.26='omega' - - do highItem=1 while @.highItem\=='' /*find how many entries. */ - end /*highitem*/ - -highItem=highItem-1 /*adjust highItem slightly. */ -return -/*──────────────────────────────────SHOW@ subroutine────────────────────*/ -show@: widthH=length(highItem) /*maximum width of any line. */ - - do j=1 for highItem - say 'element' right(j,widthH) arg(1)':' @.j - end /*j*/ -say copies('-', 79) /*show a separator line. */ -return diff --git a/Task/Sorting-algorithms-Quicksort/Mathematica/sorting-algorithms-quicksort.math b/Task/Sorting-algorithms-Quicksort/Mathematica/sorting-algorithms-quicksort.math deleted file mode 100644 index d0e87fe0dd..0000000000 --- a/Task/Sorting-algorithms-Quicksort/Mathematica/sorting-algorithms-quicksort.math +++ /dev/null @@ -1,5 +0,0 @@ -QuickSort[x_List] := Module[{pivot}, - If[Length@x <= 1, Return[x]]; - pivot = RandomChoice@x; - Flatten@{QuickSort[Cases[x, j_ /; j < pivot]], Cases[x, j_ /; j == pivot], QuickSort[Cases[x, j_ /; j > pivot]]} - ] diff --git a/Task/Sorting-algorithms-Strand-sort/D/sorting-algorithms-strand-sort.d b/Task/Sorting-algorithms-Strand-sort/D/sorting-algorithms-strand-sort.d deleted file mode 100644 index 8d85f190cb..0000000000 --- a/Task/Sorting-algorithms-Strand-sort/D/sorting-algorithms-strand-sort.d +++ /dev/null @@ -1,44 +0,0 @@ -import std.stdio, std.container; - -DList!T strandSort(T)(DList!T list) { - static DList!T merge(DList!T left, DList!T right) { - DList!T result; - while (!left.empty && !right.empty) { - if (left.front <= right.front) { - result.insertBack(left.front); - left.removeFront(); - } else { - result.insertBack(right.front); - right.removeFront(); - } - } - result.insertBack(left[]); - result.insertBack(right[]); - return result; - } - - DList!T result, sorted, leftover; - - while (!list.empty) { - leftover.clear(); - sorted.clear(); - sorted.insertBack(list.front); - list.removeFront(); - foreach (item; list) { - if (sorted.back <= item) - sorted.insertBack(item); - else - leftover.insertBack(item); - } - result = merge(sorted, result); - list = leftover; - } - - return result; -} - -void main() { - auto lst = DList!int([-2,0,-2,5,5,3,-1,-3,5,5,0,2,-4,4,2]); - foreach (e; strandSort(lst)) - write(e, " "); -} diff --git a/Task/Stack/ALGOL-68/stack.alg b/Task/Stack/ALGOL-68/stack.alg deleted file mode 100644 index f57c3e2552..0000000000 --- a/Task/Stack/ALGOL-68/stack.alg +++ /dev/null @@ -1,56 +0,0 @@ -MODE VALUE = STRING; # type of a LINK in this STACK # - -MODE LINK = STRUCT(VALUE value, REF LINK next); -MODE STACK = STRUCT(REF LINK first); - -STRUCT ( - PROC (REF STACK)VOID init, - PROC (REF STACK)BOOL non zero, - PROC (REF STACK, VALUE)VOID append, - PROC (REF STACK)VALUE pop, - PROC (REF STACK)STRING repr, - PROC (REF STACK, STRING)BOOL index error mended -) class stack = ( - # PROC init = # (REF STACK self)VOID: - first OF self := NIL, - # PROC non zero = # (REF STACK self)BOOL: - REF LINK(first OF self) ISNT NIL , - # PROC append = # (REF STACK self, VALUE value)VOID: - first OF self := HEAP LINK := (value, first OF self), - # PROC pop = # (REF STACK self)VALUE: ( - IF first OF self IS NIL THEN - STRING message = "pop from empty stack"; - IF NOT (index error mended OF class stack)(self, message) THEN - raise index error(message) - FI - FI; - VALUE out = value OF first OF self; - first OF self := next OF first OF self; - out - ), - # PROC repr = # (REF STACK self)STRING: ( - STRING out := "(", - sep := ""; - REF LINK this := first OF self; - WHILE REF LINK(this) ISNT NIL DO - out +:= sep + """" + value OF this + """"; - sep := ", "; - this := next OF this - OD; - out+")" - ), - # PROC index error mended = # (REF STACK self, STRING message)BOOL: - FALSE # no mend applied # -); - -PROC raise index error := (STRING message)VOID: stop; - -STACK stack; (init OF class stack)(stack); - -[]STRING sample = ("Was", "it", "a", "cat", "I", "saw"); - -FOR i TO UPB sample DO - (append OF class stack)(stack, sample[i]) -OD; - -print(((repr OF class stack)(stack), newline)) diff --git a/Task/Stack/REXX/stack.rexx b/Task/Stack/REXX/stack.rexx deleted file mode 100644 index 1b85ae47de..0000000000 --- a/Task/Stack/REXX/stack.rexx +++ /dev/null @@ -1,7 +0,0 @@ -y=123 /*define a REXX variable, value is 123 */ -push y /*pushes 123 onto the stack. */ -pull g /*pops last value stacked & removes it. */ -q=empty() /*invokes the EMPTY subroutine (below)*/ -exit /*stick a fork in it, we're done. */ - -empty: return queued() /*subroutine returns # of stacked items.*/ diff --git a/Task/Stack/Scala/stack.scala b/Task/Stack/Scala/stack.scala deleted file mode 100644 index f015306057..0000000000 --- a/Task/Stack/Scala/stack.scala +++ /dev/null @@ -1,18 +0,0 @@ -class Stack[T] -{ - private var items=List[T]() - - def isEmpty=items.isEmpty - - def peek=items match{ - case List() => error("Stack empty") - case head::rest => head - } - - def pop=items match{ - case List() => error("Stack empty") - case head::rest => items=rest; head - } - - def push(value:T)=items=value+:items -} diff --git a/Task/Stem-and-leaf-plot/Java/stem-and-leaf-plot.java b/Task/Stem-and-leaf-plot/Java/stem-and-leaf-plot.java deleted file mode 100644 index 9c3b000902..0000000000 --- a/Task/Stem-and-leaf-plot/Java/stem-and-leaf-plot.java +++ /dev/null @@ -1,57 +0,0 @@ -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -public class StemAndLeaf { - private static int[] data = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, - 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, - 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, - 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, - 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, - 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, - 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, - 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, - 133, 45, 120, 30, 127, 31, 116, 146 }; - - public static Map> createPlot(int... data){ - Map> plot = new TreeMap>(); - int highestStem = -1; //for filling in stems with no leaves - for(int datum:data){ - int leaf = datum % 10; - int stem = datum / 10; //integer division - if(stem > highestStem){ - highestStem = stem; - } - if(plot.containsKey(stem)){ - plot.get(stem).add(leaf); - }else{ - LinkedList list = new LinkedList(); - list.add(leaf); - plot.put(stem, list); - } - } - if(plot.keySet().size() < highestStem + 1 /*highest stem value and 0*/ ){ - for(int i = 0; i <= highestStem; i++){ - if(!plot.containsKey(i)){ - LinkedList list = new LinkedList(); - plot.put(i, list); - } - } - } - return plot; - } - - public static void printPlot(Map> plot){ - for(Map.Entry> line : plot.entrySet()){ - Collections.sort(line.getValue()); - System.out.println(line.getKey() + " | " + line.getValue()); - } - } - - public static void main(String[] args){ - Map> plot = createPlot(data); - printPlot(plot); - } -} diff --git a/Task/String-comparison/REXX/string-comparison.rexx b/Task/String-comparison/REXX/string-comparison.rexx deleted file mode 100644 index 2ed44fa537..0000000000 --- a/Task/String-comparison/REXX/string-comparison.rexx +++ /dev/null @@ -1,23 +0,0 @@ -animal = 'dog' -if animal = 'cat' then - say animal "is lexically equal to cat" -if animal != 'cat' then - say animal "is not lexically equal cat" -if animal > 'cat' then - say animal "is lexically higher than cat" -if animal < 'cat' then - say animal "is lexically lower than cat" -if animal >= 'cat' then - say animal "is not lexically lower than cat" -if animal <= 'cat' then - say animal "is not lexically higher than cat" -/* The above comparative operators do not consider - leading and trailing whitespace when making comparisons. */ -if ' cat ' = 'cat' then - say "this will print because whitespace is stripped" - -/* To consider all whitespace in a comparison - we need to use strict comparative operators */ - -if ' cat ' == 'cat' then - say "this will not print because comparison is strict" diff --git a/Task/String-comparison/UNIX-Shell/string-comparison.sh b/Task/String-comparison/UNIX-Shell/string-comparison.sh deleted file mode 100644 index 17dd300f52..0000000000 --- a/Task/String-comparison/UNIX-Shell/string-comparison.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/sh - -A=Bell -B=Ball - -# Traditional test command implementations test for equality and inequality -# but do not have a lexical comparison facility -if [ $A = $B ] ; then - echo 'The strings are equal' -fi -if [ $A != $B ] ; then - echo 'The strings are not equal' -fi - -# All variables in the shell are strings, so numeric content cause no lexical problems -# 0 , -0 , 0.0 and 00 are all lexically different if tested using the above methods. - -# However this may not be the case if other tools, such as awk are the slave instead of test. diff --git a/Task/String-concatenation/BASIC/string-concatenation.basic b/Task/String-concatenation/BASIC/string-concatenation.basic deleted file mode 100644 index 2d77564ffb..0000000000 --- a/Task/String-concatenation/BASIC/string-concatenation.basic +++ /dev/null @@ -1,4 +0,0 @@ -s$ = "hello" -print s$;" literal" 'or s$ + " literal" -s2$ = s$ + " literal" -print s2$ diff --git a/Task/String-concatenation/COBOL/string-concatenation.cobol b/Task/String-concatenation/COBOL/string-concatenation.cobol deleted file mode 100644 index 21f63d2303..0000000000 --- a/Task/String-concatenation/COBOL/string-concatenation.cobol +++ /dev/null @@ -1,15 +0,0 @@ - IDENTIFICATION DIVISION. - PROGRAM-ID. Concat. - - DATA DIVISION. - WORKING-STORAGE SECTION. - 01 Str PIC X(7) VALUE "Hello, ". - 01 Str2 PIC X(15). - - PROCEDURE DIVISION. - DISPLAY "Str : " Str - MOVE FUNCTION CONCATENATE(Str, " World!") TO Str2 - DISPLAY "Str2 : " Str2 - - GOBACK - . diff --git a/Task/String-concatenation/Nimrod/string-concatenation.nimrod b/Task/String-concatenation/Nimrod/string-concatenation.nimrod deleted file mode 100644 index 4ba9455384..0000000000 --- a/Task/String-concatenation/Nimrod/string-concatenation.nimrod +++ /dev/null @@ -1,4 +0,0 @@ -var str, str1 = "String" -echo(str & " literal.") -str1 = str1 & " literal." -echo(str1) diff --git a/Task/String-interpolation--included-/Ada/string-interpolation--included-.ada b/Task/String-interpolation--included-/Ada/string-interpolation--included-.ada deleted file mode 100644 index c38c188a13..0000000000 --- a/Task/String-interpolation--included-/Ada/string-interpolation--included-.ada +++ /dev/null @@ -1,11 +0,0 @@ -with Ada.Strings.Fixed, Ada.Text_IO; -use Ada.Strings, Ada.Text_IO; -procedure String_Replace is - Original : constant String := "Mary had a @__@ lamb."; - Tbr : constant String := "@__@"; - New_Str : constant String := "little"; - Index : Natural := Fixed.Index (Original, Tbr); -begin - Put_Line (Fixed.Replace_Slice ( - Original, Index, Index + Tbr'Length - 1, New_Str)); -end String_Replace; diff --git a/Task/String-interpolation--included-/Prolog/string-interpolation--included-.pro b/Task/String-interpolation--included-/Prolog/string-interpolation--included-.pro deleted file mode 100644 index 3ae9464f96..0000000000 --- a/Task/String-interpolation--included-/Prolog/string-interpolation--included-.pro +++ /dev/null @@ -1,3 +0,0 @@ -Extra = little, -format('Mary had a ~w lamb.', [Extra]), % display result -format(atom(Atom), 'Mary had a ~w lamb.', [Extra]). % ... or store it a variable diff --git a/Task/String-length/Ruby/string-length.rb b/Task/String-length/Ruby/string-length.rb deleted file mode 100644 index a1e56ed2df..0000000000 --- a/Task/String-length/Ruby/string-length.rb +++ /dev/null @@ -1,4 +0,0 @@ -# -*- coding: utf-8 -*- - -puts "あいうえお".bytesize -# => 15 diff --git a/Task/Sum-and-product-of-an-array/Common-Lisp/sum-and-product-of-an-array.lisp b/Task/Sum-and-product-of-an-array/Common-Lisp/sum-and-product-of-an-array.lisp deleted file mode 100644 index 1f697ca583..0000000000 --- a/Task/Sum-and-product-of-an-array/Common-Lisp/sum-and-product-of-an-array.lisp +++ /dev/null @@ -1,3 +0,0 @@ -(let ((data #(1 2 3 4 5))) ; the array - (values (reduce #'+ data) ; sum - (reduce #'* data))) ; product diff --git a/Task/Sum-and-product-of-an-array/Emacs-Lisp/sum-and-product-of-an-array.l b/Task/Sum-and-product-of-an-array/Emacs-Lisp/sum-and-product-of-an-array.l deleted file mode 100644 index cee29a0b1f..0000000000 --- a/Task/Sum-and-product-of-an-array/Emacs-Lisp/sum-and-product-of-an-array.l +++ /dev/null @@ -1,3 +0,0 @@ -(setq array [1 2 3 4 5]) -(eval (concatenate 'list '(+) array)) -(eval (concatenate 'list '(*) array)) diff --git a/Task/Sum-of-a-series/Julia/sum-of-a-series.julia b/Task/Sum-of-a-series/Julia/sum-of-a-series.julia deleted file mode 100644 index d1c2d880d7..0000000000 --- a/Task/Sum-of-a-series/Julia/sum-of-a-series.julia +++ /dev/null @@ -1,5 +0,0 @@ -julia> f(x) = sum(1/[1:x].^2) -# method added to generic function f - -julia> f(1000) -1.6439345666815615 diff --git a/Task/System-time/Scala/system-time.scala b/Task/System-time/Scala/system-time.scala deleted file mode 100644 index 26d8129d7a..0000000000 --- a/Task/System-time/Scala/system-time.scala +++ /dev/null @@ -1 +0,0 @@ -println(new java.util.Date) diff --git a/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses.rexx b/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses.rexx deleted file mode 100644 index b51922fb90..0000000000 --- a/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses.rexx +++ /dev/null @@ -1,84 +0,0 @@ -/*REXX program to create/build/list a table of US postal addresses. */ -/*┌────────────────────────────────────────────────────────────────────┐ - │ Format of an entry in the USA address/city/state/zipcode structure.│ - │ │ - │ The "structure" name can be any legal variable name, but here the │ - │ name will be shorted to make these comments (and program) easier │ - │ to read; it's name will be @USA (in any case). In addition,│ - │ the following variables names (stemmed array tails) will need to │ - │ be kept unitialized (that is, not used for any variable name). │ - │ To that end, each of these "hands-off" variable names will have a │ - │ underscore in the beginning of each name. Other possibilities are │ - │ to have a trailing underscore (or both leading and trailing), some │ - │ other special eye-catching character such as: ! @ # $ ? │ - │ │ - │ Any field not specified will have a value of "null" (length 0). │ - │ │ - │ Any field can contain any number of characters, this can be limited│ - │ by the restrictions imposed by standards or USA legal definitions. │ - │ Any number of fields could be added (with invalid field testing). │ - ├────────────────────────────────────────────────────────────────────┤ - │ @USA.0 the number of entries in the @USA "array". │ - │ │ - │ nnn is some positive integer (no leading zeros, it │ - │ can be any length). │ - ├────────────────────────────────────────────────────────────────────┤ - │ @USA.nnn._name = name of person, business, or lot description.│ - ├────────────────────────────────────────────────────────────────────┤ - │ @USA.nnn._addr = 1st street address │ - │ @USA.nnn._addr2 = 2nd street address │ - │ @USA.nnn._addr3 = 3rd street address │ - │ @USA.nnn._addrNN = ... (any number, but in sequential order). │ - ├────────────────────────────────────────────────────────────────────┤ - │ @USA.nnn._state = US postal code for the state/terrority/etc. │ - ├────────────────────────────────────────────────────────────────────┤ - │ @USA.nnn._city = offical city name, may include any char. │ - ├────────────────────────────────────────────────────────────────────┤ - │ @USA.nnn._zip = US postal zipcode, 5 digit format or │ - │ 10 char format. │ - ├────────────────────────────────────────────────────────────────────┤ - │ @USA.nnn._upHist = update History (who, date and timestamp). │ - └────────────────────────────────────────────────────────────────────┘*/ -@USA.=; @USA.0=0 - -@usa.0=@usa.0+1 /*bump the unique number for use.*/ -call @USA '_city','Boston' -call @USA '_state','MA' -call @USA '_addr',"51 Franklin Street" -call @USA '_name',"FSF Inc." -call @USA '_zip','02110-1301' - -@usa.0=@usa.0+1 /*bump the unique number for use.*/ -call @USA '_city','Washington' -call @USA '_state','DC' -call @USA '_addr',"The Oval Office" -call @USA '_addr2',"1600 Pennsylvania Avenue NW" -call @USA '_name',"The White House" -call @USA '_zip',20500 -call @USA 'list' -exit /*stick a fork in it, we're done.*/ -/*───────────────────────────────@USA subroutine────────────────────────*/ -@USA: procedure expose @USA.; parse arg what,txt; arg ?; nn=@usa.0 -if ?\=='LIST' then do - call value '@USA.'nn"."what,txt - call value '@USA.'nn".upHist",userid() date() time() - end - else do nn=1 for @usa.0 - call @USA_list - end /*nn*/ -return -/*───────────────────────────────@USA_tell subroutine───────────────────*/ -@USA_tell: _=value('@USA.'nn"."arg(1)); - if _\=='' then say right(translate(arg(1),,'_'),6) "──►" _ - return -/*───────────────────────────────@USA_list subroutine───────────────────*/ -@USA_list: call @USA_tell '_name' - call @USA_tell '_addr' - do j=2 until _=='' - call @USA_tell '_addr'j - end /*j*/ - call @USA_tell '_city' - call @USA_tell '_state' - call @USA_tell '_zip' - say copies('─',40) - return diff --git a/Task/Terminal-control-Clear-the-screen/Lua/terminal-control-clear-the-screen.lua b/Task/Terminal-control-Clear-the-screen/Lua/terminal-control-clear-the-screen.lua deleted file mode 100644 index f24fd1daad..0000000000 --- a/Task/Terminal-control-Clear-the-screen/Lua/terminal-control-clear-the-screen.lua +++ /dev/null @@ -1 +0,0 @@ -os.execute( "clear" ) diff --git a/Task/Terminal-control-Coloured-text/Python/terminal-control-coloured-text.py b/Task/Terminal-control-Coloured-text/Python/terminal-control-coloured-text.py deleted file mode 100644 index 330f53bf48..0000000000 --- a/Task/Terminal-control-Coloured-text/Python/terminal-control-coloured-text.py +++ /dev/null @@ -1,11 +0,0 @@ -from colorama import init, Fore, Back, Style -init(autoreset=True) - -print Fore.RED + "FATAL ERROR! Cannot write to /boot/vmlinuz-3.2.0-33-generic" -print Back.BLUE + Fore.YELLOW + "What a cute console!" -print "This is an %simportant%s word" % (Style.BRIGHT, Style.NORMAL) -print Fore.YELLOW + "Rosetta Code!" -print Fore.CYAN + "Rosetta Code!" -print Fore.GREEN + "Rosetta Code!" -print Fore.MAGENTA + "Rosetta Code!" -print Back.YELLOW + Fore.BLUE + Style.BRIGHT + " " * 40 + " == Good Bye!" diff --git a/Task/Test-a-function/Ada/test-a-function.ada b/Task/Test-a-function/Ada/test-a-function.ada deleted file mode 100644 index 14415f06c4..0000000000 --- a/Task/Test-a-function/Ada/test-a-function.ada +++ /dev/null @@ -1,28 +0,0 @@ -with Ada.Text_IO; - -procedure Test_Function is - - function Palindrome (Text : String) return Boolean is - begin - for Offset in 0 .. Text'Length / 2 - 1 loop - if Text (Text'First + Offset) /= Text (Text'Last - Offset) then - return False; - end if; - end loop; - return True; - end Palindrome; - - str1 : String := "racecar"; - str2 : String := "wombat"; - -begin - begin - pragma Assert(False); -- raises an exception if assertions are switched on - Ada.Text_IO.Put_Line("Skipping the test! Please compile with assertions switched on!"); - exception - when others => -- assertions are switched on -- perform the tests - pragma Assert (Palindrome (str1) = True, "Assertion on str1 failed"); - pragma Assert (Palindrome (str2) = False, "Assertion on str2 failed"); - Ada.Text_IO.Put_Line("Test Passed!"); - end; -end Test_Function; diff --git a/Task/Tic-tac-toe/Java/tic-tac-toe.java b/Task/Tic-tac-toe/Java/tic-tac-toe.java deleted file mode 100644 index 3cc0c8d41d..0000000000 --- a/Task/Tic-tac-toe/Java/tic-tac-toe.java +++ /dev/null @@ -1,152 +0,0 @@ -import java.util.Scanner; -import java.util.Random; -import java.util.InputMismatchException; - -public class TicTacToe -{ - public static char [] gameBoard = {'1', '2', '3', '4', '5', - '6', '7', '8', '9'}; - public static Scanner keyboard = new Scanner(System.in); - private static int[][] wins = { - {0,1,2}, - {3,4,5}, - {6,7,8}, - {0,4,8}, - {2,4,6}, - {0,3,6}, - {1,4,7}, - {2,5,8} - }; - - public static void main (String [] args) - { - System.out.println("*****Tic-Tac-Toe*****"); - System.out.println("Directions:\n" - + "Tic-Tac-Toe game board has 9 possible marking positions " - + "labeled 1-9.\nTo begin play enter desired position " - + "number to mark with X.\n"); - - outputBoard(); - makeMove(); - - int moveCount = 1; - - while(moveCount < gameBoard.length) - { - computerMove(); - if(checkBoard()){ - System.out.println("Computer wins!"); - break; - } - makeMove(); - if(checkBoard()){ - System.out.println("Player wins!"); - break; - } - - moveCount = moveCount + 2; - } - } - - public static void outputBoard() - { - System.out.println("+---+---+---+"); - System.out.println("| " + gameBoard[0] + " | " + gameBoard[1] - + " | " + gameBoard[2] + " |"); - System.out.println("+---+---+---+"); - System.out.println("| " + gameBoard[3] + " | " + gameBoard[4] - + " | " + gameBoard[5] + " |"); - System.out.println("+---+---+---+"); - System.out.println("| " + gameBoard[6] + " | " + gameBoard[7] - + " | " + gameBoard[8] + " |"); - System.out.println("+---+---+---+"); - } - - public static void makeMove() - { - - System.out.println("\nYour Turn, Enter Position #:"); - int num = getPosition(); - - if(gameBoard[num] == 'X' || gameBoard[num] == 'O') - { - System.out.println("Board Position Already Taken, Try Again."); - makeMove(); - } - else - { - gameBoard[num] = 'X'; - outputBoard(); - } - - } - - public static int getPosition() - { - int num = 0; - boolean done = false; - - do - { - try - { - num = keyboard.nextInt(); - - if(num > gameBoard.length || num <= 0) - { - System.out.println("Incorrect Position Try Again"); - } - else - done = true; - } - catch(InputMismatchException exception) - { - System.out.println("Incorrect Entry Format Try Again"); - keyboard.next(); - } - - }while(!done); - - return num - 1; - } - - - public static void computerMove() - { - Random rand = new Random(); - int num = rand.nextInt(9); - - if(gameBoard[num] == ('X') || gameBoard[num] == ('O')) - computerMove(); - else - { - System.out.println("\nComputer's Turn."); - gameBoard[num] = 'O'; - outputBoard(); - } - } - - public static boolean checkBoard() - { - for(int[] win:wins) - { - if(gameBoard[win[0]] != 'O' && gameBoard[win[0]] != 'X') - { - continue; - } - - char winner = gameBoard[win[0]]; - - boolean check = true; - - for(int pos:win) - { - check = check && (gameBoard[pos] == winner); - } - - if(check) - return true; - } - return false; - } -} diff --git a/Task/Tokenize-a-string/Perl-6/tokenize-a-string.pl6 b/Task/Tokenize-a-string/Perl-6/tokenize-a-string.pl6 deleted file mode 100644 index 92481405f3..0000000000 --- a/Task/Tokenize-a-string/Perl-6/tokenize-a-string.pl6 +++ /dev/null @@ -1 +0,0 @@ -'Hello,How,Are,You,Today'.split(',').join('.').say; diff --git a/Task/User-input-Text/BASIC/user-input-text.basic b/Task/User-input-Text/BASIC/user-input-text.basic deleted file mode 100644 index 672c8c2c7b..0000000000 --- a/Task/User-input-Text/BASIC/user-input-text.basic +++ /dev/null @@ -1,2 +0,0 @@ -INPUT "Enter a string"; s$ -INPUT "Enter a number: ", i% diff --git a/Task/Vampire-number/Python/vampire-number.py b/Task/Vampire-number/Python/vampire-number.py deleted file mode 100644 index 033627cb76..0000000000 --- a/Task/Vampire-number/Python/vampire-number.py +++ /dev/null @@ -1,75 +0,0 @@ -import math -from operator import mul -from itertools import product -from functools import reduce - - -def fac(n): - '''\ - return the prime factors for n - >>> fac(600) - [5, 5, 3, 2, 2, 2] - >>> fac(1000) - [5, 5, 5, 2, 2, 2] - >>> - ''' - step = lambda x: 1 + x*4 - (x//2)*2 - maxq = int(math.floor(math.sqrt(n))) - d = 1 - q = n % 2 == 0 and 2 or 3 - while q <= maxq and n % q != 0: - q = step(d) - d += 1 - res = [] - if q <= maxq: - res.extend(fac(n//q)) - res.extend(fac(q)) - else: res=[n] - return res - -def fact(n): - '''\ - return the prime factors and their multiplicities for n - >>> fact(600) - [(2, 3), (3, 1), (5, 2)] - >>> fact(1000) - [(2, 3), (5, 3)] - >>> - ''' - res = fac(n) - return [(c, res.count(c)) for c in set(res)] - -def divisors(n): - 'Returns all the divisors of n' - factors = fact(n) # [(primefactor, multiplicity), ...] - primes, maxpowers = zip(*factors) - powerranges = (range(m+1) for m in maxpowers) - powers = product(*powerranges) - return ( - reduce(mul, - (prime**power for prime, power in zip(primes, powergroup)), - 1) - for powergroup in powers) - -def vampire(n): - fangsets = set( frozenset([d, n//d]) - for d in divisors(n) - if (len(str(d)) == len(str(n))/2 - and sorted(str(d) + str(n//d)) == sorted(str(n)) - and (str(d)[-1] == 0) + (str(n//d)[-1] == 0) <=1) ) - return sorted(tuple(sorted(fangs)) for fangs in fangsets) - - -if __name__ == '__main__': - print('First 25 vampire numbers') - count = n = 0 - while count <25: - n += 1 - fangpairs = vampire(n) - if fangpairs: - count += 1 - print('%i: %r' % (n, fangpairs)) - print('\nSpecific checks for fangpairs') - for n in (16758243290880, 24959017348650, 14593825548650): - fangpairs = vampire(n) - print('%i: %r' % (n, fangpairs)) diff --git a/Task/Variables/BASIC/variables.basic b/Task/Variables/BASIC/variables.basic deleted file mode 100644 index 28d0944c8a..0000000000 --- a/Task/Variables/BASIC/variables.basic +++ /dev/null @@ -1,16 +0,0 @@ -10 LET A=1.3 -20 LET B%=1.3: REM THE SIGIL INDICATES AN INTEGER, SO THIS WILL BE ROUNDED DOWN -30 LET C$="0121": REM THE SIGIL INDICATES A STRING DATA TYPE. THE LEADING ZERO IS NOT TRUNCATED -40 DIM D(10): REM CREATE AN ARRAY OF 10 DIGITS -50 DIM E$(5.10): REM CREATE AN ARRAY OF 5 STRINGS, WITH A MAXIMUM LENGTH OF 10 CHARACTERS -60 LET D(1)=1.3: REM ASSIGN THE FIRST ELEMENT OF D -70 LET E$(3)="ROSE": REM ASSIGN A VALUE TO THE THIRD STRING -80 PRINT D(3): REM UNASSIGNED ARRAY ELEMENTS HAVE A DEFAULT VALUE OF ZERO -90 PRINT E$(3): REM TEN SPACES BECAUSE STRING ARRAYS ARE NOT DYNAMIC -100 PRINT E$(3);"TTA CODE": REM THERE WILL BE SPACES BETWEEN ROSE AND ETTA -110 DIM F%(10):REM INTEGERS USE LESS SPACE THAN FLOATING POINT VALUES -120 PRINT G: REM THIS IS AN ERROR BECAUSE F HAS NOT BEEN DEFINED -130 PRINT D(0): REM THIS IS AN ERROR BECAUSE ELEMENTS ARE NUMBERED FROM ONE -140 LET D(11)=6: REM THIS IS AN ERROR BECAUSE D ONLY HAS 10 ELEMENTS -150 PRINT F%: REM THIS IS AN ERROR BECAUSE WE HAVE NOT PROVIDED AN ELEMENT NUMBER -160 END diff --git a/Task/Variables/C++/variables.cpp b/Task/Variables/C++/variables.cpp deleted file mode 100644 index 4e610c04d5..0000000000 --- a/Task/Variables/C++/variables.cpp +++ /dev/null @@ -1 +0,0 @@ -int a; diff --git a/Task/Vigen-re-cipher/D/vigen-re-cipher.d b/Task/Vigen-re-cipher/D/vigen-re-cipher.d deleted file mode 100644 index 7d2fc88813..0000000000 --- a/Task/Vigen-re-cipher/D/vigen-re-cipher.d +++ /dev/null @@ -1,29 +0,0 @@ -import std.stdio, std.string; - -string encrypt(in string txt, in string key) pure -in { - assert(key.removechars("^A-Z") == key); -} body { - string res; - foreach (immutable i, immutable c; toUpper(txt).removechars("^A-Z")) - res ~= (c + key[i % $] - 2 * 'A') % 26 + 'A'; - return res; -} - -string decrypt(in string txt, in string key) pure -in { - assert(key.removechars("^A-Z") == key); -} body { - string res; - foreach (immutable i, immutable c; toUpper(txt).removechars("^A-Z")) - res ~= (c - key[i % $] + 26) % 26 + 'A'; - return res; -} - -void main() { - immutable key = "VIGENERECIPHER"; - immutable original = "Beware the Jabberwock, my son!" ~ - " The jaws that bite, the claws that catch!"; - immutable encoded = original.encrypt(key); - writeln(encoded, "\n", encoded.decrypt(key)); -} diff --git a/Task/Visualize-a-tree/Python/visualize-a-tree.py b/Task/Visualize-a-tree/Python/visualize-a-tree.py deleted file mode 100644 index 4eaf4c9aeb..0000000000 --- a/Task/Visualize-a-tree/Python/visualize-a-tree.py +++ /dev/null @@ -1,48 +0,0 @@ -Python 3.2.3 (default, May 3 2012, 15:54:42) -[GCC 4.6.3] on linux2 -Type "copyright", "credits" or "license()" for more information. ->>> help('pprint.pprint') -Help on function pprint in pprint: - -pprint.pprint = pprint(object, stream=None, indent=1, width=80, depth=None) - Pretty-print a Python object to a stream [default is sys.stdout]. - ->>> from pprint import pprint ->>> for tree in [ (1, 2, 3, 4, 5, 6, 7, 8), - (1, (( 2, 3 ), (4, (5, ((6, 7), 8))))), - ((((1, 2), 3), 4), 5, 6, 7, 8) ]: - print("\nTree %r can be pprint'd as:" % (tree, )) - pprint(tree, indent=1, width=1) - - - -Tree (1, 2, 3, 4, 5, 6, 7, 8) can be pprint'd as: -(1, - 2, - 3, - 4, - 5, - 6, - 7, - 8) - -Tree (1, ((2, 3), (4, (5, ((6, 7), 8))))) can be pprint'd as: -(1, - ((2, - 3), - (4, - (5, - ((6, - 7), - 8))))) - -Tree ((((1, 2), 3), 4), 5, 6, 7, 8) can be pprint'd as: -((((1, - 2), - 3), - 4), - 5, - 6, - 7, - 8) ->>> diff --git a/Task/Walk-a-directory-Recursively/Ruby/walk-a-directory-recursively.rb b/Task/Walk-a-directory-Recursively/Ruby/walk-a-directory-recursively.rb deleted file mode 100644 index 78070306a5..0000000000 --- a/Task/Walk-a-directory-Recursively/Ruby/walk-a-directory-recursively.rb +++ /dev/null @@ -1,6 +0,0 @@ -require 'find' - -Find.find('/your/path') do |f| - # print file and path to screen if filename ends in ".mp3" - puts f if f.match(/\.mp3\Z/) -end diff --git a/Task/Web-scraping/Common-Lisp/web-scraping.lisp b/Task/Web-scraping/Common-Lisp/web-scraping.lisp deleted file mode 100644 index a3bd3e53d2..0000000000 --- a/Task/Web-scraping/Common-Lisp/web-scraping.lisp +++ /dev/null @@ -1,10 +0,0 @@ -BOA> (let* ((url "http://tycho.usno.navy.mil/cgi-bin/timer.pl") - (regexp (load-time-value - (cl-ppcre:create-scanner "(?m)^.{4}(.+? UTC)"))) - (data (drakma:http-request url))) - (multiple-value-bind (start end start-regs end-regs) - (cl-ppcre:scan regexp data) - (declare (ignore end)) - (when start - (subseq data (aref start-regs 0) (aref end-regs 0))))) -"Aug. 12, 04:29:51 UTC" diff --git a/Task/Word-wrap/D/word-wrap.d b/Task/Word-wrap/D/word-wrap.d deleted file mode 100644 index 7122375bc8..0000000000 --- a/Task/Word-wrap/D/word-wrap.d +++ /dev/null @@ -1,35 +0,0 @@ -import std.algorithm; - -string wrap(in string text, in int lineWidth) { - auto words = text.splitter(); - if (words.empty) return ""; - string wrapped = words.front; - words.popFront(); - int spaceLeft = lineWidth - wrapped.length; - foreach (word; words) - if (word.length + 1 > spaceLeft) { - wrapped ~= "\n" ~ word; - spaceLeft = lineWidth - word.length; - } else { - wrapped ~= " " ~ word; - spaceLeft -= 1 + word.length; - } - return wrapped; -} - -void main() { - immutable frog = -"In olden times when wishing still helped one, there lived a king -whose daughters were all beautiful, but the youngest was so beautiful -that the sun itself, which has seen so much, was astonished whenever -it shone in her face. Close by the king's castle lay a great dark -forest, and under an old lime-tree in the forest was a well, and when -the day was very warm, the king's child went out into the forest and -sat down by the side of the cool fountain, and when she was bored she -took a golden ball, and threw it up on high and caught it, and this -ball was her favorite plaything."; - - import std.stdio; - foreach (width; [72, 80]) - writefln("Wrapped at %d:\n%s\n", width, wrap(frog, width)); -} diff --git a/Task/Word-wrap/REXX/word-wrap.rexx b/Task/Word-wrap/REXX/word-wrap.rexx deleted file mode 100644 index bf58e97d45..0000000000 --- a/Task/Word-wrap/REXX/word-wrap.rexx +++ /dev/null @@ -1,37 +0,0 @@ -/*REXX program justifies (by words) a string of words ───► screen. */ -arg justify width . /*───────────JUSTIFY─────────────*/ - /*Center: ◄centered► */ - /* Both: ◄──both margins──► */ - /* Right: ────────►right margin */ - /* Left: left margin◄──────── */ - /*═════pick one of the above.════*/ - -just=left(justify,1) /*only use first capital letter. */ - -if width=='' then width=linesize()%2 /*It's null? Then pick a default*/ -if width==0 then width=40 /*Not determinable? Then use 40.*/ - -txt="Diplomacy is the art of saying 'Nice Doggy' until", - "you can find a rock. ─── Will Rodgers" - -$='' /*this is where the money is. */ - - do k=1 for words(txt); x=word(txt,k) /*parse 'til we exhaust the TXT. */ - _=$ x /*append it to da money and see. */ - if length(_)►width then call tell /*word(s) exceeded the width? */ - $=_ /*the new words are OK so far. */ - end - -call tell /*handle any residual words. */ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────TELL subroutine─────────────────────*/ -tell: if $=='' then return /*first word may be too long. */ - select - when just=='B' then $=justify($,width) /*◄────both────►*/ - when just=='C' then $= center($,width) /* ◄centered► */ - when just=='R' then $= right($,width) /*──────► right */ - otherwise $= strip($) /*left ◄────────*/ - end /*select*/ - say $ /*show and tell, or write──►file?*/ - _=x /*handle any word overflow. */ - return /*go back and keep truckin'. */ diff --git a/Task/XML-Output/BASIC/xml-output.basic b/Task/XML-Output/BASIC/xml-output.basic deleted file mode 100644 index 0ebbcb64bd..0000000000 --- a/Task/XML-Output/BASIC/xml-output.basic +++ /dev/null @@ -1,40 +0,0 @@ -Data "April", "Bubbly: I'm > Tam and <= Emily", _ - "Tam O'Shanter", "Burns: ""When chapman billies leave the street ...""", _ - "Emily", "Short & shrift" - -Declare Function xmlquote(ByRef s As String) As String -Dim n As Integer, dev As String, remark As String - -Print "" -For n = 0 to 2 - Read dev, remark - Print " "; _ - xmlquote(remark); "" -Next -Print "" - -End - -Function xmlquote(ByRef s As String) As String - Dim n As Integer - Dim r As String - For n = 0 To Len(s) - Dim c As String - c = Mid(s,n,1) - Select Case As Const Asc(c) - Case Asc("<") - r = r + "<" - Case Asc(">") - r = r + ">" - Case Asc("&") - r = r + "&" - Case Asc("""") - r = r + """ - Case Asc("'") - r = r + "'" - Case Else - r = r + c - End Select - Next - Function = r -End Function diff --git a/Task/Yin-and-yang/D/yin-and-yang.d b/Task/Yin-and-yang/D/yin-and-yang.d deleted file mode 100644 index 05ec4e0b04..0000000000 --- a/Task/Yin-and-yang/D/yin-and-yang.d +++ /dev/null @@ -1,47 +0,0 @@ -import std.stdio, std.string, std.algorithm, std.array; - -struct SquareBoard { - enum W : char { Void=' ', Yan='.', Yin='#', I='?' } - - immutable int scale; - W[][] pix; - - this(in int s) pure nothrow { - scale = s; - pix = new typeof(pix)(s * 12 + 1, s * 12 + 1); - } - - string toString() const /*pure nothrow*/ { - auto rows = pix.map!q{ (cast(char[])a).idup }(); - return rows.join("\n"); - } - - void drawCircle(Draw)(in int cx, in int cy, in int cr, - Draw action) -pure nothrow { - immutable rr = (cr * scale) ^^ 2; - foreach (y, ref r; pix) - foreach (x, ref v; r) { - immutable dx = x - cx * scale; - immutable dy = y - cy * scale; - if (dx ^^ 2 + dy ^^ 2 <= rr) - v = action(x); - } - } - - SquareBoard yanYin() pure nothrow { - foreach (r; pix) // clear - r[] = W.Void; - drawCircle(6, 6, 6, (int x) => (x < 6 * scale) ? W.Yan : W.Yin); - drawCircle(6, 3, 3, (int x) => W.Yan); - drawCircle(6, 9, 3, (int x) => W.Yin); - drawCircle(6, 9, 1, (int x) => W.Yan); - drawCircle(6, 3, 1, (int x) => W.Yin); - return this; - } -} - -void main() { - writeln(SquareBoard(2).yanYin()); - writeln(SquareBoard(1).yanYin()); -} diff --git a/Task/Zig-zag-matrix/D/zig-zag-matrix.d b/Task/Zig-zag-matrix/D/zig-zag-matrix.d deleted file mode 100644 index a4a14aef0a..0000000000 --- a/Task/Zig-zag-matrix/D/zig-zag-matrix.d +++ /dev/null @@ -1,22 +0,0 @@ -int[][] zigZag(in int n) pure nothrow { - static void move(in int n, ref int i, ref int j) pure nothrow { - if (j < n - 1) { - if (i > 0) i--; - j++; - } else - i++; - } - - auto a = new int[][](n, n); - int x, y; - foreach (v; 0 .. n ^^ 2) { - a[y][x] = v; - (x + y) % 2 ? move(n, x, y) : move(n, y, x); - } - return a; -} - -void main() { - import std.stdio; - writefln("%(%(%2d %)\n%)", zigZag(5)); -}